要筛选多列的MySQL查询?

时间:2013-04-22 11:00:32

标签: mysql select where

假设我有1个表只有多列。让我们说:

Fruits
--------------------------------------
id  | name        | country
--------------------------------------
1   | Banana      | china
2   | Orange      | japan
3   | Apple       | japan
4   | Apple       | china
5   | Banana      | usa
6   | Orange      | china

然后简单查询SELECT所有水果id < 6 它是:

SELECT * FROM fruits WHERE id < 6

然后它将返回:

--------------------------------------
id  | name        | country
--------------------------------------
1   | Banana      | china
2   | Orange      | japan
3   | Apple       | japan
4   | Apple       | china
5   | Banana      | usa

然后通过附上上述查询,我​​怎样才能继续排除更多内容 例如:

Do NOT want to see, any "APPLE" from "CHINA".

所以最终结果必须是:

--------------------------------------
id  | name        | country
--------------------------------------
1   | Banana      | china
2   | Orange      | japan
3   | Apple       | japan
5   | Banana      | usa

这又是withoutif, name='Apple' AND country='china'的行

  • 因此,通过继续第一个查询,我如何添加额外的“ AND条件对”才能获得此结果?

我会说:

SELECT * FROM fruits WHERE id < 6 ... AND DON'T RETURN this condition where name='Apple' and country='china' TOGETHER

2 个答案:

答案 0 :(得分:2)

尝试:

SELECT * 
FROM fruits 
WHERE (id < 6)
AND NOT (name = 'Apple' AND country = 'china')

或者:

SELECT * 
FROM fruits 
WHERE (id < 6)
AND id NOT IN (SELECT id 
               FROM fruits
               WHERE name = 'Apple'
               AND country = 'china')

答案 1 :(得分:1)

试试这个

 SELECT * FROM fruits WHERE 
                 (name ,country) not in ( select 'Apple' ,'china' from Fruits)

 HAVING id < 6

DEMO HERE