选择不同行中具有匹配条件的记录

时间:2016-12-08 15:10:13

标签: mysql sql

假设我有一个SQL表table1

+--------------------------+
| id | person |   eats     |
+----+--------+------------+
|  1 |   1    |   apple    |
|  2 |   3    |  banana    |    
|  3 |   2    |  orange    |
|  4 |   1    | strawberry |
|  5 |   2    |   grapes   |
|  6 |   4    |   apple    |
+----+--------+------------+

我想让所有同时吃apple并说strawberry的人。

我试过

select person 
from table1
where eats in( 'apple', 'strawberry' )

但是此查询返回1, 1, 4,我猜是因为它正在单独检查applestrawberry

如何让所有同时吃applestrawberry的人?

2 个答案:

答案 0 :(得分:5)

SELECT person 
FROM table1
WHERE eats IN( 'apple', 'strawberry' )
GROUP BY person
HAVING COUNT(DISTINCT eats)=2

更新对我来说,查询解释了自己。但既然你要求解释我们一起试试:

您的原始查询会返回此结果:

1
1
4

但是你不想得到两次,这意味着你应该按person对结果进行分组,这会将我们带到下一个查询:

SELECT person 
FROM table1
WHERE eats IN( 'apple', 'strawberry' )
GROUP BY person

将返回:

1
4

但你不想要person=4,因为它只匹配apple,所以最简单的方法就是将eats计算为:{/ p>

SELECT person, count(distinct eats)
FROM table1
WHERE eats IN( 'apple', 'strawberry' )
GROUP BY person

然后我们得到了这个结果:

person  count(distinct eats)
1        2
4        1

我们已准备好过滤此结果集以仅获得具有2(苹果和草莓)的人:

SELECT person, count(distinct eats)
FROM table1
WHERE eats IN( 'apple', 'strawberry' )
GROUP BY person
HAVING count(distinct eats) = 2

这将返回:

person  count(distinct eats)
1        2

但您没有要求count这就是我从count(distinct eats) ed字段列表中删除SELECT部分的原因。

http://sqlfiddle.com/#!9/ea612/6

答案 1 :(得分:3)

person分组,只收集组中两个记录的

select person 
from table1
where eats in( 'apple', 'strawberry' )
group by person
having count(*) = 2