SQL GROUP BY“HAVING”所需的行

时间:2016-09-09 13:52:55

标签: mysql sql having

是否有使用HAVING检查所需行是否在GROUP BY范围内的简洁方法?

使用示例日期:

turtle_id   name  
1           Mike
2           Ralph
3           Leo
4           Don

turtle_id   crush_for
1           Pizza
1           April Oneil
2           April Oneil
3           Pizza
3           April Oneil
4           Pizza
4           Pizza
4           Science
4           April Oneil

和SQL:

SELECT turtle.name
FROM turtle
JOIN turtle_crush ON turtle_crush.turtle_id = turtle.turtle_id
WHERE turtle_crush.crush_for IN ('Pizza', 'April Oneil')
GROUP BY turtle.turtle_id
HAVING (a crush on both "Pizza" and "April Oneil")

我意识到我可以做HAVING COUNT(*) > 1这样的事情,但这会给Don(id 4)带来误报,因为他喜欢'Pizza'两次。

修改 只需添加一个WHERE子句就会返回拉尔夫,他没有crush_for'披萨'

2 个答案:

答案 0 :(得分:5)

这应该有效:

SELECT t.turtle_name
FROM turtle t
INNER JOIN (SELECT turtle_id
            FROM turtle_crush
            WHERE crush_for IN ('Pizza','April Oneil')
            GROUP BY turtle_id
            HAVING COUNT(DISTINCT crush_for) = 2) tc
    on t.turtle_id = tc.turtle_id;

在此代码中,子查询首先过滤crush_for'Pizza''April Oneil'的结果。然后按turtle_id进行分组,另一个条件是选择那些具有2个不同turtle_id值的crush_for(因此确保您只获得同时具有两个turtle_id值的turtle )。然后它与create procedure表联合以获取名称。

答案 1 :(得分:1)

将粉碎列表放在WHERE子句中,按龟ID分组,计算粉碎类型的不同值,然后只保留至少有2个值的组(或者在查询中放入多少粉碎) ):

SELECT turtle.name
FROM turtle
  INNER JOIN turtle_crush ON turtle_crush.turtle_id = turtle.turtle_id
WHERE crush_for IN ("Pizza", "April Oneil")
GROUP BY turtle.turtle_id
HAVING COUNT(DISTINCT crush_for) = 2