sql left join的问题

时间:2011-04-21 20:49:22

标签: sql

我构建了3个表

tb1 for book
tb2 for sub subject
tb3 for main subject

每本书有1个子科目,每个科目有1个主题 我想在book =>之间加入联接sub subject =>主题

我在书与子科目之间加入,但不能在主题与子科目之间进行

select book.id, book.titl, subsubject.title, mainsubject.title
from book
left join subsubject on book.id = subsubject.book_id

我希望完成此声明以添加主题

4 个答案:

答案 0 :(得分:1)

哇,我想我明白了...... 你想要这样的东西:

SELECT book.id, book.titl, subsubject.title, mainsubject.title FROM book,subsubject,mainsubject WHERE book.id = subsubject.book_id AND subsubject.book_id=mainsubject.book_id

您可以使用;

重新发送WHERE

LEFT JOIN subsubject on book.id = subsubject.book_id LEFT JOIN mainsubject on book.id = mainsubject.book_id

另外,你的意思是book.title?

(我的SQL可能不完美,但应该工作)

答案 1 :(得分:0)

试试这个:

select book.id, book.titl, subsubject.title, mainsubject.title
from book
left join subsubject on book.id = subsubject.book_id
left join mainsubject on subsubject.book_id=mainsubject.book_id

答案 2 :(得分:0)

诀窍可能是你需要在sub和main之间使用不同的连接条件而不是book和sub之间的连接条件:

select *
from book join sub on book.id = sub.book_id
    join main on sub.sub_id = main.sub_id

我不确定为什么如果每本书必须有一个主题并且每个主题都需要一个主题,则需要左(=外)联接。

答案 3 :(得分:0)

尝试:

select b.id, b.title, s.title, m.title
from book b
left join subsubject s
  on s.id = b.ss_id
left join mainsubject m
  on m.id = b.m_id
where b.id = (id of book you'd like)

希望这有帮助。