[英]MySQL: List data with its related data from other tables if available
這是我的情況:
表image_book_rel
包含兩個表之間的關系,即book_table
和image_table
。
我需要從表book_table
獲取書籍列表,並從表image_table
獲取相關圖像數據( 如果有) 。
這些表格大致如下所示(簡化):
/* book_table */
id title price
-------- ---------- ------
1 Book 1 $10
2 Book 2 $13
3 Book 3 $15
4 Book 4 $20
5 Book 5 $12
6 Book 6 $10
7 Book 7 $14
/* image_table */
id description file
-------- ---------------- -------------
20 Image of Book 2 book_img2.jpg
30 Image of Book 3 book_img3.jpg
50 book_img5.jpg
70 Image of Book 7 book_img7.jpg
/* image_book_rel */
id book_id image_id
-------- --------- ---------
1 2 20
2 3 30
3 5 50
4 7 70
這是我查詢結果所需要的:
/* Expected result: */
book_id image_id filename book_title img_desc
-------- --------- --------------- ----------- -----------------
1 Book 1
2 20 book_img2.jpg Book 2 Image of Book 2
3 30 book_img3.jpg Book 3 Image of Book 3
4 Book 4
5 50 book_img5.jpg Book 5
6 Book 6
7 70 book_img7.jpg Book 7 Image of Book 7
這是我嘗試過的:
SELECT bk.id AS book_id, im.id AS image_id, im.file AS filename, bk.title AS book_title, im.description AS img_desc
FROM book_table AS bk
LEFT JOIN image_book_rel AS bi
ON bk.id = bi.book_id
LEFT JOIN image_table AS im
ON bi.image_id = im.id
WHERE bk.id = bk.id
AND bi.book_id = bk.id
AND bi.image_id = im.id
ORDER BY bk.id
上面查詢的結果僅檢索具有圖像的書。 我需要檢索所有書籍。 我該怎么辦?
不帶WHERE
情況下嘗試使用IFNULL
將空值替換為空字符串:
SELECT IFNULL(bk.id,'') AS book_id, IFNULL(im.id,'') AS image_id, IFNULL(im.file,'') AS filename, IFNULL(bk.title,'') AS book_title, IFNULL(im.description,'') AS img_desc
FROM book_table AS bk
LEFT JOIN image_book_rel AS bi
ON bk.id = bi.book_id
LEFT JOIN image_table AS im
ON bi.image_id = im.id
ORDER BY bk.id
結果:
BOOK_ID IMAGE_ID FILENAME BOOK_TITLE IMG_DESC
1 Book 1
2 20 book_img2.jpg Book 2 Image of Book 2
3 30 book_img3.jpg Book 3 Image of Book 3
4 Book 4
5 50 book_img5.jpg Book 5
6 Book 6
7 70 book_img7.jpg Book 7 Image of Book 7
在SQL Fiddle中查看結果。
您正在混合兩種JOIN語法。 您擁有的WHERE子句正在復制LEFT JOIN子句(這是您想要的),但是它等效於實現INNER JOIN,它排除了沒有圖像的行。
正確的查詢要簡單得多:
SELECT bk.id AS book_id, im.id AS image_id, im.file AS filename, bk.title AS book_title, im.description AS img_desc
FROM book_table AS bk
LEFT JOIN image_book_rel AS bi
ON bk.id = bi.book_id
LEFT JOIN image_table AS im
ON bi.image_id = im.id
ORDER BY bk.id
為了進一步完善答案... WHERE條件
bk.id = bk.id
是絕對沒用的,而WHERE條件:
bi.book_id = bk.id
bi.image_id = im.id
通過濾除具有NULL im.id的行,使您指定的LEFT JOINS無效。 這些條件強制執行與查詢相同的結果:
SELECT bk.id AS book_id, im.id AS image_id, im.file AS filename, bk.title AS book_title, im.description AS img_desc
FROM book_table AS bk
JOIN image_book_rel AS bi
ON bk.id = bi.book_id
JOIN image_table AS im
ON bi.image_id = im.id
ORDER BY bk.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.