嵌套选择和DISTINCT / ORDER的性能

时间:2016-06-28 23:03:24

标签: sql sql-server

我的原始查询是:

SELECT DISTINCT
Member.Id,
Member.Email,
Booking.ItemId
FROM Member WITH(NOLOCK)
JOIN Booking WITH(NOLOCK) ON Member.Id = Booking.CustomerId
WHERE DATEDIFF(d, Booking.BookingDate, GETUTCDATE()) > 1

我尝试通过Booking.BookingDate订购结果,并在返回的结果中添加了Booking.BookingDate相关信息作为新列:

因此,新查询将如下所示:

SELECT *
FROM
(
SELECT DISTINCT
Member.Id,
Member.Email,
Booking.ItemId,
Booking.BookingDate
FROM Member WITH(NOLOCK)
JOIN Booking WITH(NOLOCK) ON Member.Id = Booking.CustomerId
WHERE DATEDIFF(d, Booking.BookingDate, GETUTCDATE()) > 2   
) a
Order by BookingDate 

我使用SSMS的执行计划来比较这两个查询,它们看起来是一样的。    有什么方法可以确保我的重写不会让性能变慢吗?

1 个答案:

答案 0 :(得分:1)

您不需要子查询(尽管这不会影响性能)。所以:

SELECT DISTINCT m.Id, m.Email, b.ItemId, b.BookingDate
FROM Member m JOIN
     Booking b
     ON m.Id = b.CustomerId
WHERE b.BookingDate > DATEADD(day, 1, GETUTCDATE())
ORDER BY BookingDate;

我真的怀疑你需要SELECT DISTINCT,因为重复似乎不太可能。请注意,表别名使查询更容易编写和读取。