简体   繁体   English

连接3个表php / sql时出错

[英]Error joining 3 tables php/sql

I'm new to this, so I know I'm missing something simple, but I can't figure it out. 我对此并不陌生,所以我知道我缺少一些简单的东西,但我无法弄清楚。 I'm trying to join 3 tables together and I've got it working with 2 joins, but when combined in the same query, there ends up being an error. 我正在尝试将3个表连接在一起,并且已经将其与2个连接一起使用,但是当在同一查询中组合时,最终会出现错误。

My 3 tables are: 我的3张桌子是:

TBL_Authors TBL_Authors

Author_ID
Author_Name

TBL_Publishers TBL_Publishers

Publisher_ID
Publisher_Name

TBL_Books TBL_Books

Title
Author_ID
Publisher_ID
ISBN
Genre
Price
Cost
Rating

What I have that isn't working: 我有什么不起作用:

    $query = 'SELECT * FROM TBL_PUBLISHERS
              JOIN TBL_BOOKS ON TBL_PUBLISHERS.Publisher_ID = TBL_BOOKS.Publisher_ID

              SELECT * FROM TBL_AUTHORS
              JOIN TBL_BOOKS ON TBL_AUTHORS.Author_ID = TBL_BOOKS.Author_ID

              ORDER BY TBL_BOOKS.Title ASC;';

This query assumes that each book was published. 该查询假定每本书都已出版。

SELECT 
   * 
FROM 
   TBL_Books b
   INNER JOIN TBL_Publishers p ON b.Publisher_ID = p.Publisher_ID
   INNER JOIN TBL_Authors a ON b.Author_ID = a.Author_ID 
ORDER BY 
   b.Title

Book will always have an Author, but not necessarily a Publisher, if it's not published. 如果未出版,则书籍将始终具有作者,但不一定具有出版者。 If you need to fetch all the books irrespective of whether published or not, you will have to change INNER join on TBL_Publishers to LEFT . 如果您需要获取所有书籍,无论是否出版,都必须将TBL_Publishers上的INNER join TBL_PublishersLEFT

This Query Will show you the result of all details of book, publisher name, author name. 该查询将向您显示书籍,出版者名称,作者名称的所有详细信息的结果。

SELECT 
t1.* , t2.Publisher_Name , t3.Author_Name 
FROM 
TBL_Books as t1 
INNER JOIN TBL_Publishers as t2 ON t1.Publisher_ID = t2.Publisher_ID
INNER JOIN TBL_Authors as t3 ON t1.Author_ID = t2.Author_ID 
ORDER BY 
t1.Title

Check This and update if this query helps you. 选中此并更新此查询是否对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM