我有一个名为Languages
的表,它存储了Persons
表中存储的每个人能够说话的语言,然后我有一个名为Homework
的表,它存储了每个人的所有作业必须这样做,但与语言有关。我能够选择1要为语言1(左连接)做的家庭作业,但也希望能够在同一查询中选择语言人1能够说话。有人能给我一个提示如何实现这一目标吗?左边的语言连接会搞乱结果,因为它会弄乱家庭作业表上的语言。
语言和人数很多,家庭作业和人员也是如此。
当我添加第二个left join
:
SELECT p.id, l.id, h.id
FROM Persons AS p
LEFT JOIN Homework AS h ON h.person_id = p.id
#LEFT JOIN Languages AS l ON l.person_id = p.id #Screws the result multipliying by the number of available languages
WHERE p.id = 1
AND h.language_id = 1
我想结合上面的查询和以下内容:
SELECT *
FROM languages
WHERE person_id=1
答案 0 :(得分:1)
你想找到吗?
Person | Language | Homework
------------------------------
Bob | English |
Bob | French |
Bob | Spanish | Geography
James | English |
James | French | History
James | Spanish |
使用此...
SELECT p.id, l.id, h.id
FROM Persons AS p
LEFT JOIN Languages AS l ON l.person_id = p.id
LEFT JOIN Homework AS h ON h.language_id = l.id
And h.person_id = p.id
或者
Person | Language | Homework
------------------------------
Bob | Spanish | Geography
James | French | History
我相信已经提出的建议
更新:现在应该为您提供所有语言的人,但只显示与您想要的语言匹配的家庭作业
SELECT p.id, l.id, h.id
FROM Persons AS p
LEFT JOIN Languages AS l ON l.person_id = p.id
LEFT JOIN Homework AS h ON h.language_id = l.id
And h.person_id = p.id
And h.language_id = 1