跨3个表的SQL查询

时间:2019-03-06 07:53:38

标签: mysql sql

我在弄清楚如何在下一个情景中执行SQL查询时遇到问题。

我有3张桌子,如下所示:

TABLE.BOOKS

book_id |   title           |   author          |   language
-------------------------------------------------------------
1       |   Title one       |   Author, One     |   english  
2       |   Another title   |   Second, Name    |   french

TABLE.PUBLISHERS

publ_id |   publisher       |   city    
---------------------------------------------
1       |   Company one     |   Munich  
2       |   Books ltd       |   London  
41      |   WEpublish co    |   Paris

TABLE.BOOK_PUBLISHER

book_id |   publ_id
---------------------
1       |   2  
2       |   41

在上面的表格中,我想编写一个查询,该查询将从添加了出版商数据的books表中返回我的数据,如下所示:

['Title one', 'Author, One', 'english', 'Books ltd', 'London']  
['Another title', 'Second, Name', 'french', 'WEpublish co', 'Paris']

任何人都可以建议我,这种SQL查询的外观如何?谢谢。

3 个答案:

答案 0 :(得分:3)

这是从JOINbooks通过publishers的基本book_publisher

SELECT b.title, b.author, b.language, p.publisher, p.city
FROM books b
JOIN book_publisher bp ON bp.book_id = b.book_id
JOIN publishers p ON p.publ_id = bp.publ_id

输出:

title           author          language    publisher       city
Title one       Author, One     english     Books ltd       London
Another title   Second, Name    french      WEpublish co    Paris

Demo on dbfiddle

答案 1 :(得分:1)

您必须JOIN这三个表才能得到结果。

select title,author,language,publisher,city
from BOOKS
join BOOK_PUBLISHER on BOOK_PUBLISHER.book_id = BOOKS.book_id
join PUBLISHERS on PUBLISHERS.publ_id = BOOK_PUBLISHER.publ_id

答案 2 :(得分:0)

您可以通过以下查询进行操作:

select b.title,b.author,b.language,p.publisher,p.city from Table1 b join Table3 pb on pb.book_id=b.book_id join Table2 p ON p.publ_id = pb.publ_id