提问者:小点点

在php mysql中,如何使用“and”查询获得多行


id - idProduct - idFilter
65 -    494    -    3
66 -    495    -    3
67 -    497    -    17
68 -    500    -    17
69 -    500    -    3

我如何获得所有idFilter 17和3的idProducts。 在这种情况下,这只是id为500的产品

我尝试这样做:$query=“Select idProduct FROM tablename WHERE(idFilter='3')或(idFilter='17')GROUP BY idProduct”;

我知道这很愚蠢,但我不知道?

谢谢


共1个答案

匿名用户

如果您需要比较单个coloum上的多个行值,则该值应满足ANS条件。 然后你可以做以下的技巧来达到这个目的。

SELECT distinct(idProduct) as idProduct,count(*) AS total FROM  tablename 
        WHERE idFilter IN (17,3) GROUP BY idProduct  
        HAVING total = 2; 
        //Having will force result to have both 17 and 3  else 17 or 3 alone will be in the result

如果对上述ID使用php变量,可以尝试以下操作

$inArray = array(17,3);
$sql = "SELECT distinct(idProduct) as idProduct,count(*) AS total FROM  tablename 
        WHERE idFilter IN (".implode(',',$inArray).") GROUP BY idProduct  
        HAVING total = '".count($inArray)."'";