我正在尝试了解如何有效地将谓词逻辑转换为SQL查询。我被困在:
For all P(x), (for all P(y), (Knows(x,y) -> Likes(x,y)))
我进一步将其翻译为:
-exists P(x), (exists P(y), (Knows(x,y) /\ -Likes(x,y)))
用作“公式”:
for all x, (A -> B) <=> -exists x, (A /\ -B); for all x, (A) <=> -exists x, (-A)
出现错误的机率如下:
Write a query that returns the name of all persons that like everyone they know.
其中Knows和Likes表不是对称的,仅包含Person表的外键,因此表达Person X Knows / Like PersonY。
上面的SQL SELECT查询的外观如何?
我已经尝试过了,但是没有用:
SELECT P.name
FROM Persons P
WHERE NOT EXISTS (
SELECT *
FROM Knows K
WHERE K.personB_id NOT IN (
SELECT L.personB_id
FROM Likes L
WHERE K.personA_id = L.personA_id
AND K.personB_id <> L.personB_id))
最佳答案
查找认识自己不喜欢的人的人的名单。然后从不在该集合中的人中选择。
SELECT FROM Persons
WHERE Persons.ID NOT IN (
SELECT Knows.PersonA
FROM Knows LEFT JOIN Likes
ON Knows.PersonA = Likes.PersonA
AND Knows.PersonB = Likes.PersonB
WHERE Likes.PersonB is null
)