MySQL LEFT JOIN 3表
我有3个表格:
人员(PersonID,姓名,SS) 恐惧(恐惧,恐惧) Person_Fear(ID,PersonID,FearID)
现在我想列出每一个与他们有任何恐惧的人(可以是多种恐惧,但也可以是没有)。 即使一个人没有与他们有关的恐惧,人桌也必须显示出来。
我想我需要做一个左连接,但我的代码似乎不工作:
SELECT persons.name, persons.ss, fears.fear FROM persons LEFT JOIN fears ON person_fear.personid = person_fear.fearid
我在这里做错了什么? 提前致谢。
您正试图将Person_Fear.PersonID
joinPerson_Fear.PersonID
– 这并不合理。 你可能想要像这样的东西:
SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons LEFT JOIN Person_Fear INNER JOIN Fears ON Person_Fear.FearID = Fears.FearID ON Person_Fear.PersonID = Persons.PersonID
这通过中间表Person_Fear
join到人们的Fears
。 因为Persons
和Person_Fear
之间的连接是一个LEFT JOIN
,你将得到所有Persons
logging。
或者:
SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons LEFT JOIN Person_Fear ON Person_Fear.PersonID = Persons.PersonID LEFT JOIN Fears ON Person_Fear.FearID = Fears.FearID
尝试这个
SELECT p.Name, p.SS, f.Fear FROM Persons p LEFT JOIN Person_Fear fp ON p.PersonID = fp.PersonID LEFT JOIN Fear f ON f.FearID = fp.FearID
试试这个绝对的工作。
SELECT p.PersonID AS person_id, p.Name, p.SS, f.FearID AS fear_id, f.Fear FROM person_fear AS pf LEFT JOIN persons AS p ON pf.PersonID = p.PersonID LEFT JOIN fears AS f ON pf.PersonID = f.FearID WHERE f.FearID = pf.FearID AND p.PersonID = pf.PersonID
Select p.Name, p.SS, f.fear From Persons p left join Person_Fear pf inner join Fears f on pf.fearID = f.fearID on p.personID = pf.PersonID