2012-04-30 98 views
1

我對錶進行規範化相當陌生,而且我正在爲了從3個表中獲取正確的信息而帶來一些麻煩。我舉了一個例子,從不同的圖書館預訂書籍。我有3張桌子。書籍,地點,預訂(見下表):加入多個表

//SQL query: 
$sql = 
"SELECT * FROM books 
JOIN (location LEFT JOIN reservations ON location.locID = reservations.locID) 
ON books.bookID = location.bookID 
WHERE location.locID=2 
"; 

,我希望能實現,如果我要列出校園B中的書籍輸出:

title |locName |status 
Book 1|Campus B|1 
Book 2|Campus B|0 
Book 3|Campus B|0 
Book 4|Campus B|0 
Book 5|Campus B|1 

出於某種原因,我肯定沒有得到我認爲我應該得到的輸出結果,如果有人有任何建議,我很好奇。我敢肯定,一旦我看到發生了什麼,我會明白我做錯了什麼。

table: books 
bookID|title 
    1 | Book 1 
    2 | Book 2 
    3 | Book 3 
    4 | Book 4 
    5 | Book 5 


table: location 
locID|locName 
    1 | campus A 
    2 | campus B 
    3 | campus C 


table: reservations 
bookID|locID|status 
    1 | 1 | 1 
    3 | 1 | 1 
    4 | 1 | 1 
    1 | 2 | 1 
    5 | 2 | 1 
    4 | 3 | 1 
    5 | 3 | 1 

回答

3

我覺得這是更符合你在找什麼:

SELECT * 
FROM books b 
LEFT JOIN reservations r ON b.bookID = r.bookID 
JOIN location l on r.locID = l.locID 
WHERE l.locID = 2 

這將返回在與LOCID = 2的位置保留的書單。

在這種情況下,我有一個LEFT JOIN保留原始查詢,但鑑於你的WHERE子句與在location.locID領域NULL任何記錄將不被選中。

因此,我可以重新編寫查詢所有內連接,就像這樣:

SELECT * 
FROM books b 
JOIN reservations r ON b.bookID = r.bookID 
JOIN location l on r.locID = l.locID 
WHERE l.locID = 2 

,你可能會感興趣的其他查詢:

得到所有的書籍,無論他們是否被保留的任何地方:

SELECT * 
FROM books b 
LEFT JOIN reservations r ON b.bookID = r.bookID 
JOIN location l on r.locID = l.locID 

得到的所有位置,而不管是否有保留有書:

SELECT * 
FROM books b 
JOIN reservations r ON b.bookID = r.bookID 
RIGHT JOIN location l on r.locID = l.locID 

得到所有書籍和所有位置:

SELECT * 
FROM books b 
LEFT JOIN reservations r ON b.bookID = r.bookID 
RIGHT JOIN location l on r.locID = l.locID 
+0

喔...我知道了。好吧,這真的很有幫助!謝謝 – Skyros

0
SELECT 
books.title 
, location.locName 
, IFNULL(reservations.status, 0) status 
FROM 
books 
JOIN location 
LEFT JOIN reservations ON (
    location.locID = reservations.locID 
    AND books.bookID = location.bookID 
) 
WHERE location.locID = 2