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
4

2 回答 2

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
于 2012-04-30T16:37:03.030 回答
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
于 2012-04-30T16:49:10.017 回答