MySQL缩短查询 - 具有多个OR选项的SELECT

时间:2011-09-26 18:33:47

标签: mysql

这是我的查询

SELECT FB_TEXT
FROM `FB_DATA`
WHERE `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID = 1

我想要做的是允许多个FB_TYPEID,因此查询应该是:

AND FB_TYPEID = 1,2,7 

1,2和7是我需要的数字。如何在不进行长时间查询的情况下写出来:

SELECT FB_TEXT
FROM `FB_DATA`
WHERE `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID = 1 OR `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID = 2 OR `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID = 7

3 个答案:

答案 0 :(得分:3)

使用IN代替=

WHERE `FB_MODELID` = "'.$sku_modelid.'" AND FB_TYPEID IN (1,2,7)

答案 1 :(得分:1)

IN()运算符是正确答案,但如果您不想(或不能)使用IN(),则无需重复模型ID。此查询与IN()解决方案等效。

SELECT FB_TEXT
FROM `FB_DATA`
WHERE `FB_MODELID` = "'.$sku_modelid.'" AND (FB_TYPEID = 1 OR FB_TYPEID = 2 OR FB_TYPEID = 7)

答案 2 :(得分:0)

使用IN()

WHERE `FB_MODELID` = ? AND FB_TYPEID IN (1,2,7)

(ps在查询中使用占位符来防止SQL注入攻击)