我有以下数据库结构:
我有任务:为包含少于3本书的订单选择买方名称,订单ID和书名。我解决了这个任务:
SELECT b.Name, O.OrderId, bk.Name
FROM Orders O
JOIN Buyers b ON b.Id = O.BuyerId
JOIN BooksInOrder bo ON bo.OrderId = O.OrderId
JOIN Books bk ON bk.Id = bo.BookId
WHERE O.OrderId IN
(
SELECT OrderId
FROM BooksInOrder
GROUP BY ORDERID
HAVING COUNT(*) < 3
)
我的SQL是执行我想要实现的目标的最佳方式吗?
答案 0 :(得分:0)
通常,了解性能的唯一方法是使用您的数据在系统上运行查询。好的,有些东西会影响性能(比如不必要的select distinct
或union
而不是union all
)。但是,您的查询没有。
一个明显的简化是将where
子句移动到from
子句:
SELECT b.Name, O.OrderId, bk.Name
FROM (SELECT OrderId
FROM BooksInOrder
GROUP BY ORDERID
HAVING COUNT(*) < 3
) o JOIN
Buyers b
ON b.Id = O.BuyerId JOIN
BooksInOrder bo
ON bo.OrderId = O.OrderId JOIN
Books bk
ON bk.Id = bo.BookId;
请注意,虽然这可能看起来更简单,但性能可能不会更好。
同样,您可以使用窗口函数:
SELECT Name, OrderId, BookName
FROM (SELECT b.Name, O.OrderId, bk.Name as BookName, count(*) over (partition by orderid) as cnt
FROM Orders O JOIN
Buyers b
ON b.Id = O.BuyerId JOIN
BooksInOrder bo
ON bo.OrderId = O.OrderId JOIN
Books bk
ON bk.Id = bo.BookId
) bb
WHERE cnt <= 3;
但是你原来的配方可能仍然效果最佳。