HAVING 查询的问题

Problems with HAVING query

我正在学习有关数据库的在线课程。但是,我不知道如何继续这个问题。谁能帮忙?这是我的代码:

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

A 和 B 的知识总是不同的 table,对吧?如果是这样,那么您不应该在这两个条件下都加入。

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

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
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

但是如果您想知道如何使用 having

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