所以我有这三个表:
Persons {id, name}
Knows {A_id, B_id} - (Person A knows Person B)
Smoking {id} - (id -> Persons{id})
Persons:
{1, "Tim"}
{2, "Kim"}
{3, "Jim"}
{4, "Rim"}
Knows:
{1, 2}
{1, 3}
{3, 2}
{3, 4}
Smoking:
{3}
我需要{3,“Jim”}才能归还,因为他不知道有谁吸烟({1,“Tim”}知道Jim吸烟所以他出去了)
我尝试了这个查询:
SELECT P.name
FROM Persons P, Knows K
WHERE K.A_id = P.id AND K.B_id NOT IN (SELECT id FROM Smokes)
但它仍然会回归“蒂姆”,即使他知道2个人,其中只有1个人在吸烟。而且我只需要那些“我的朋友”不吸烟的人......帮助!
答案 0 :(得分:2)
请允许我解释如何在集合论/ SQL术语中思考您的问题:
这导致:
select P.Name
from Persons P inner join Knows K on K.A_Id = P.ID
left join Smoking on Smoking.ID = P.B_Id
group by person
having sum(smoking.ID) = 0
答案 1 :(得分:1)
SELECT p.name
FROM Persons p
WHERE NOT EXISTS ( -- there does not exist
SELECT * FROM Knows k -- a person I know
JOIN smokes s ON s.id = k.b_id -- who smokes
WHERE k.A_id = p.id
);
答案 2 :(得分:0)
我认为找到所有知道吸烟者然后反转结果的人会更容易找到所有不认识吸烟者的人,而不是试图找到所有人。
select *
from persons P
LEFT JOIN smoking s
INNER JOIN knows k
on k.B_id = s.id
on k.A_id = P.id
where s.id is null
Knows和Smoker之间的内部联系将运行以找到所有知道吸烟者的人。然后where子句将过滤所有知道吸烟者的人。