鑑於表collections
和表books
,我需要一個查詢來獲取其所有圖書的單個集合,但前提是至少有一本書是cover_image=1
。從WHERE子句中的連接表中使用COUNT
使事情複雜化的是collections
和books
之間的多對多關係。有第三張表rel_collections_books
,它們將兩者聯繫在一起。任何書都可以是多個不同集合的一部分。
一個給定的集合中獲取的所有圖書查詢:
$id = 7; //the collection we want to fetch
SELECT b.*
FROM books b
LEFT JOIN rel_collections_books rel ON rel.book__id = b.id
AND rel.collection__id = '{$id}'
LEFT JOIN collections c ON c.id = rel.collection__id
WHERE c.id = '{$id}'
到目前爲止是這種情況,但是當我運行一個查詢,它仍然產生一個結果,它應該返回null,而不是:
//none of the books in the collection have cover_image=1,
//so this query should produce nothing, but it does:
SELECT b.*
FROM books b
LEFT JOIN rel_collections_books rel ON rel.book__id = b.id
AND rel.collection__id = '{$id}'
LEFT JOIN collections c ON c.id = rel.collection__id
WHERE c.id = '{$id}'
AND EXISTS(
SELECT NULL
FROM books b
LEFT JOIN rel_collections_books rel ON rel.book__id = b.id
AND rel.collection__id = '{$id}'
WHERE b.cover_image = '1'
)
我該怎麼做,和/或有沒有更好的方法來做到這一點?謝謝。
當LEFT JOIN,把右側表的條件在ON子句中得到真正的左聯接行爲。 (在WHERE時,你會得到正常的內部連接結果。) – jarlh
注意 - 很高興知道!感謝您的建議。 – bobsoap