加入多个表格

时间:2012-04-30 16:31:54

标签: mysql join database-design multiple-tables normalize

我对表格规范化很陌生,而且我在绕着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

2 个答案:

答案 0 :(得分: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的记录。

因此,我可以使用所有INNER连接重写您的查询,如下所示:

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

答案 1 :(得分: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