MySQL或在查询中

时间:2011-11-17 20:10:27

标签: php mysql

我可以在mysql语句中使用“OR”来检查多个选项的字段值吗?

    //THE QUESTION IF HAVE IS HOW DO I DO SOMETHING LIKE BELOW  MAINLY THE "1 OR 2 OR 3 OR 4" PART.

    $sql = "SELECT email FROM USER_INFO WHERE storeID = '$storeNUM' AND region = '1 OR 2 OR 3 OR 4'";
   $results2 = $db->query($sql);

5 个答案:

答案 0 :(得分:8)

您可以使用IN作为多个OR测试的简写。

SELECT email
    FROM USER_INFO
    WHERE storeID = '$storeNUM'
        AND region IN (1,2,3,4);

答案 1 :(得分:4)

这就是你如何做这样的比赛:

... AND region IN (1,2,2,4)

答案 2 :(得分:0)

您可以使用:

$sql = "SELECT email FROM USER_INFO WHERE storeID = '$storeNUM' AND (region = 1 OR region = 2 OR region = 3 OR region = 4)";

答案 3 :(得分:0)

你可以使用数组和implode来获得一个很好的解决方案:

$regions = array( 1, 2, 3, 4);
$sql = 'SELECT email FROM USER_INFO WHERE storeID = "$storeNUM" AND ( region = ' . implode( ' OR region = ', $regions) . ' )';
echo $sql;

<强>输出:

SELECT email FROM USER_INFO WHERE storeID = "$storeNUM" AND ( region = 1 OR region = 2 OR region = 3 OR region = 4 )

Demo

答案 4 :(得分:-1)

如果region是一个字符串,你可以使用它,但它确实没有理由:

$sql = "SELECT email FROM USER_INFO WHERE storeID = '$storeNUM' AND region REGEXP '1|2|3|4'";
$results2 = $db->query($sql);