Search code examples
mysqlsqlexistsforall

Problems with HAVING query


I am following an online course on databases. However, I don't know how to proceed with this question. Can anyone help? This is my code:

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


Solution

  • 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