我第一次参加SQL课程,但在使用leebooks.sql
文件编写查询时遇到了问题。我遇到了一个解决方案,但我很好奇,因为我找到的解决方案都缩写了所有的表和列。当我尝试重写没有缩写的查询时,我的教授更喜欢,我得到一个错误,表示表不存在。我以为我正确地重写了它,带缩写的查询工作正常。如果需要,我不知道在哪里上传SQL文件?以下是查询:
缩写:
SELECT b.Title, bo.OrderDate,bo.OrderID
FROM BOOKS b
LEFT OUTER JOIN ORDER_ITEMS oi
ON b.BookID = oi.BookID
LEFT OUTER JOIN BOOK_ORDER bo
ON oi.OrderID = bo.OrderID
ORDER BY oi.BOOKID DESC;
没有缩写:
SELECT BOOKS.Title, BOOK_ORDER.OrderDate, BOOK_ORDER.OrderID
FROM BOOKS
LEFT OUTER JOIN ORDER_ITEMS.OrderID
ON BOOKS.BookID = ORDER_ITEMS.BookID
LEFT OUTER JOIN BOOK_ORDER
ON ORDER_ITEMS.OrderID = BOOK_ORDER.OrderID
ORDER BY ORDER_ITEMS.BookID DESC;
我不明白为什么第二个不起作用,而第一个不起作用,如果它们基本上是相同的东西。我错过了什么?
答案 0 :(得分:2)
联接应该在表上执行,而不是在列上执行。您的LEFT OUTER JOIN ORDER_ITEMS.OrderID
条款应为LEFT OUTER JOIN ORDER_ITEMS
。完整查询,没有表别名:
SELECT BOOKS.Title, BOOK_ORDER.OrderDate, BOOK_ORDER.OrderID
FROM BOOKS
LEFT OUTER JOIN ORDER_ITEMS ON BOOKS.BookID = ORDER_ITEMS.BookID
LEFT OUTER JOIN BOOK_ORDER ON ORDER_ITEMS.OrderID = BOOK_ORDER.OrderID
ORDER BY ORDER_ITEMS.BookID DESC;
答案 1 :(得分:1)
'别名',无论'table' AS tableAlias
还是列(table.column
AS columnAlias
)都是文字替换。
有一个表名(ORDER_ITEMS
)替换为列名(ORDER_ITEMS.OrderID
)。即JOIN ORDER_ITEMS.OrderID
代替:加入ORDER_ITEMS
...
你拥有什么,使用'别名'我添加了' AS'尝试并明确的关键字。
SELECT `b`.title,
`bo`.orderdate,
`bo`.orderid
FROM books AS `b`
LEFT OUTER JOIN order_items AS `oi`
ON `b`.bookid = `oi`.bookid
LEFT OUTER JOIN book_order AS `bo`
ON `oi`.orderid = `bo`.orderid
ORDER BY `oi`.bookid DESC;
这是有效的SQL。我用过' AS'和反引号突出显示'别名'。
表别名列表:
b
=> books
oi
=> order_items
bo
=> book_order
因此,请将所有table aliases
替换为table names
。在这里,我使用表名称的反引号来表示替换。
SELECT `books`.title,
`book_order`.orderdate,
`book_order`.orderid
FROM `books`
LEFT OUTER JOIN `order_items`
ON `books`.bookid = `order_items`.bookid
LEFT OUTER JOIN `book_order`
ON `order_items`.orderid = `book_order`.orderid
ORDER BY `order_items`.bookid DESC;
它是表名或列名的文本替换。