在Mysql PHP查询中结合Where子句

时间:2014-06-14 15:26:14

标签: php mysql sql

我有2个名为Classifieds的表,下面的Classifieds_meta是classifieds_meta表的屏幕截图

CLICK TO SEE THE SCREENSHOT

我正在编写一个搜索过滤器函数,其中包含muliple where子句,如

SELECT *,classifieds.id as id 
FROM classifieds,classifieds_meta 
WHERE (category=2 OR category=3 OR category=4 OR category=5) 
AND ((meta_key='vehicle_make' and meta_value=3 OR meta_key='vehicle_make' and meta_value=4)
AND meta_key='vehicle_mileage' and meta_value=9 OR meta_key='vehicle_mileage' and meta_value=10 OR meta_key='vehicle_mileage' and meta_value=11 ) 
AND classifieds.id=classifieds_meta.classifieds_id 
GROUP BY classifieds.id

但上面的sql语句IGNORES vehicle_makemeta_valuemeta_key字段条件,并显示不正确的结果,我想要实现的目标是我想获得类别所在的车辆(2,3,4或5)和meta_key是vehicle_make,meta_value是3或4,meta_key是vehicle_mileage,meta_value是9,10或11。

有人可以帮我形成更好的SQL语句以获得正确的结果

3 个答案:

答案 0 :(得分:2)

我想您正在寻找类别为2,3,4或5且(meta_key为vehicle_make且(meta_value为3或4))或(meta_key为vehicle_mileage且(meta_value为9,10或11))的车辆

在这种情况下,查询应为:

SELECT *,classifieds.id as id
FROM classifieds,classifieds_meta 
WHERE (category=2 OR category=3 OR category=4 OR category=5) 
AND  ((meta_key='vehicle_make' AND ( meta_value=2 OR meta_value=4)) OR (meta_key='vehicle_mileage' AND (meta_value=9 OR meta_value=10 OR meta_value=11)))

使用括号使您的语句可理解,最后在SQL查询中使用相同的括号。

编辑:

如果你想使用IN,那么查询将是:

SELECT *,classifieds.id as id
FROM classifieds,classifieds_meta 
WHERE category IN (2, 3, 4, 5) 
AND  ((meta_key='vehicle_make' AND  meta_value IN (2,4)) OR (meta_key='vehicle_mileage' AND meta_value IN (9, 10, 11)))

答案 1 :(得分:1)

我认为您正在寻找having子句而不是where。您正在尝试跨多行查找条件:

SELECT *, c.id as id 
FROM classifieds c join
     classifieds_meta  cm
     on c.id = cm.classifieds_id 
GROUP BY c.id
HAVING sum(meta_key = 'vehicle_make' and meta_value in (3, 4)) > 0 and
       sum(meta_key = 'vehicle_mileage' and meta_value in (9, 10, 11)) > 0 and
       sum(category in (2, 3, 4, 5)) > 0

> 0表示至少有一行符合每个条件。

请注意,我还修改了连接以使用显式join语法。

答案 2 :(得分:0)

这基本上就是你所拥有的(不包括表连接和类别过滤器):

((meta_key='vehicle_make' and meta_value IN (3,4)) AND meta_key='vehicle_mileage' and meta_value=9)
    OR 
(meta_key='vehicle_mileage' and meta_value IN (10, 11))

因此,vehicle_make部分是不可能的,因为meta_value从不是(3 OR 4)和9。

我认为你的目标是:

(meta_key='vehicle_make' and meta_value IN (3,4))
    OR 
(meta_key='vehicle_mileage' and meta_value IN (9, 10, 11))

现在一起:

WHERE classifieds.id=classifieds_meta.classifieds_id AND category IN (2, 3, 4, 5)
AND (
    (meta_key='vehicle_make' and meta_value IN (3,4))
        OR 
    (meta_key='vehicle_mileage' and meta_value IN (9, 10, 11))
)

从中获得的是运营商优先权。在OR之前评估AND对。