Search code examples
mysqlsqlexistsforall

FOR ALL/EXIST Queries


I am following an online course on databases. However, I really don't know what the next step is and how I can answer this question. Can anyone please help? This is what I have so far.

SELECT P.name
FROM Persons P 
LEFT JOIN Knows K ON K.personA_id = P.id
WHERE K.age >= P.age

enter image description here


Solution

  • Try this :

    SQL Fiddle

    SELECT distinct P1.name
    FROM Persons P1 
    INNER JOIN Knows K ON K.personA_id = P1.id
    INNER JOIN Persons P2 ON K.personB_id = P2.id AND P1.age - P2.age > 5
    

    It will output everybody that knows 1 person or more (personA) and that every person known is more than 5 years younger (personB)