多个联接独立但不在一起工作

时间:2017-01-27 02:22:26

标签: sql join outer-join

我试图获取来自名为book_info和copy_info的表的行信息的结果,然后(如果它们存在)来自名为publisher(其外键在copy_info中)的表的结果,并且(如果它们存在)结果从表名类型通过名为books_genres的联结表。下面,$ safe_copy_id是在php语句中定义的,为了示例,我把它保留了下来。

这有效:

SELECT * FROM book_info, copy_info
LEFT OUTER JOIN publisher ON copy_info.publisher_id = publisher.publisher_id
WHERE book_info.book_id = copy_info.book_id
AND copy_info.copy_id = $safe_copy_id LIMIT 1

这有效:

SELECT * FROM book_info, copy_info, books_genres
LEFT OUTER JOIN genre ON books_genres.genre_id = genre.genre_id
WHERE book_info.book_id = copy_info.book_id
AND copy_info.copy_id = $safe_copy_id LIMIT 1

但我真正想要的是:

SELECT * FROM book_info, copy_info, books_genres
LEFT OUTER JOIN publisher ON copy_info.publisher_id = publisher.publisher_id
LEFT OUTER JOIN genre ON books_genres.genre_id = genre.genre_id
WHERE book_info.book_id = copy_info.book_id
AND copy_info.copy_id = $safe_copy_id LIMIT 1

我应该在这里筑巢吗?不确定如何前进,并希望任何见解。

2 个答案:

答案 0 :(得分:0)

正确使用JOIN

SELECT *
FROM book_info bi JOIN
     copy_info ci
     ON bi.book_id = ci.book_id JOIN
     publisher p
     ON ci.publisher_id = p.publisher_id JOIN
     books_genres bg
     ON bg.book_id = bi.book_id JOIN  -- your question doesn't specify the JOIN condition here
     genre g
     ON bg.genre_id = g.genre_id
WHERE ci.copy_id = $safe_copy_id
LIMIT 1;

您错过了book_genres的加入。也许它与book_info相关联。

另外,我认为没有理由为查询使用外连接。我怀疑所有表都有有效的外键关系。

答案 1 :(得分:0)

感谢Gordon Linoff和Utsav指出我没有加入book_genres。以下是实际有效的查询:

 SELECT * FROM
book_info bi JOIN copy_info ci
 ON bi.book_id = ci.book_id
 LEFT OUTER JOIN publisher p
 ON ci.publisher_id = p.publisher_id
 LEFT OUTER JOIN books_genres bg
 ON bg.book_id = bi.book_id
 LEFT OUTER JOIN genre g
 ON bg.genre_id = g.genre_id
WHERE ci.copy_id = $safe_copy_id
LIMIT 1;