这是一个带有非常小的样本数据的测试示例,它显示了三种方法。
要获得最佳查询计划:
按 (GroupID, EntryDate.) 在 People 上放置一个非唯一索引。
A. 使用原始伪代码(按顺序执行但不显示日期)或
B. 使用 top 1 子查询来获取和显示日期。
A 和 B 的查询计划相同。
使用 People 表的左连接和 max() 将导致扫描(最多在 GroupID 内)获得最大值,而不是对索引中的单行进行探测。
set nocount on
if object_id('Groups') is not null drop table Groups
if object_id('People') is not null drop table People
go
-- set up tables
create table Groups
(
ID int primary key,
Name varchar(20)
)
create table People
(
ID int,
GroupID int,
EntryDate datetime
)
-- make an index that is ordered by Group, EntryDate
create index IE_GroupDate on People(GroupID, EntryDate)
-- Sample data
insert into Groups (ID, Name)
values
(1, 'Group1'),
(2, 'Group2'),
(3, 'GroupC')
insert into People (ID, GroupID, EntryDate)
values
(1, 1, '2012-01-01'),
(2, 1, '2012-02-01'),
(1, 3, '2007-12-31')
-- Queries
-- Equivalent to the original poster's intent. Note that it doesn't actually
-- show the entry date
select *
from Groups G
order by (
select top 1 EntryDate
from People P
where P.GroupID = G.ID order by EntryDate desc)
-- Same query (by query plan) but includes the EntryDate in the result set
select
G.ID,
G.Name,
LatestEntryDate = Latest.EntryDate
from Groups G
outer apply (
select top 1 EntryDate
from People P
where P.GroupID = G.ID
order by EntryDate desc
) Latest
order by LatestEntryDate
-- Query using left join. This causes a scan of the left join table to
-- compute the max. (The optimizer isn't smart enough to turn this into
-- a TOP 1)
select
G.ID,
G.Name,
LatestEntryDate = max(P.EntryDate)
from Groups G
left join People P on P.GroupID = G.ID
group by G.ID, G.Name
order by max(P.EntryDate)