HAVING查询的问题

时间:2015-03-03 18:26:34

标签: mysql sql exists forall

我正在关注数据库的在线课程。但是,我不知道如何处理这个问题。有人可以帮忙吗?这是我的代码:

SELECT distinct name
FROM Persons P, Knows K
WHERE K.personA_id = P.id AND K.personB_id = P.id
GROUP BY name
HAVING SUM(K.id) = 2

enter image description here

3 个答案:

答案 0 :(得分:3)

SELECT P.name
FROM Persons P
WHERE  (  SELECT COUNT(*)
          FROM Knows K JOIN Persons P2 ON K.personB_id = P2.id
          WHERE K.personA_id = P.id
          AND P2.age >= 60
      ) = 2

但是如果你想知道如何使用

SELECT P.name
FROM Persons P JOIN Knows K ON K.personA_id = P.id 
JOIN Persons P2 ON P2.id = K.personB_id
WHERE P2.age >= 60
GROUP BY P.id
HAVING COUNT(*)=2

请注意,此查询仅适用于MySql

答案 1 :(得分:1)

人物A和人物B在Knows表中总是不同的,对吧?如果是这样,那么你不应该加入这两个条件。

我建议您删除" AND K.personB_id = P.id"

答案 2 :(得分:1)

SELECT distinct p.name
FROM Knows K
LEFT JOIN Persons P,
ON K.personA_id = P.id 
WHERE K.personB_id 
  IN (
    SELECT id
    FROM Persons
    WHERE age>60
  )
GROUP BY name
HAVING COUNT(K.personB_id) = 2