说我有这样一张桌子:
+----------+--------+
| brand | vehicle|
+----------+--------+
| ford | car |
| ford | truck |
| ford | suv |
+----------+--------+
我想编写一个只在所有3行符合条件时才返回品牌的查询。例如,如果我说“给我带有汽车的品牌,而不是卡车或suv”,我希望查询不返回任何内容,因为“福特”全部都是3.不幸的是,我构建的查询不起作用:< / p>
SELECT brand
FROM table
WHERE vehicle='car'
AND vehicle != 'truck'
AND vehicle != 'suv';
查询返回“ford”。我理解为什么会这样做。它测试了每行的条件,第1行通过,因此返回第1行的品牌。但是,如何构建查询以执行我想要的操作?
答案 0 :(得分:2)
您需要针对每个条件
加入同一个表SELECT t1.brand
FROM table t1
LEFT JOIN table t2 ON (t1.brand = t2.brand AND t2.vehicle = 'truck')
LEFT JOIN table t3 ON (t1.brand = t3.brand AND t3.vehicle = 'suv')
WHERE t1.vehicle = 'car' AND t2.brand IS NULL AND t3.brand IS NULL
答案 1 :(得分:1)
最常用的方法是允许检查任意数量的条件,将条件放在HAVING
子句中。
SELECT brand
FROM table_name
GROUP BY brand
HAVING MAX(vehicle = 'car') = 1
AND MAX(vehicle = 'truck') = 0
AND MAX(vehicle = 'suv') = 0;
这是 SQLFiddle 演示