[英]Most efficient way to select the max value of a column and the corresponding data for that row
As a starting point I have the following query. 首先,我有以下查询。 I know that it works and produces the result I'm looking for but could it be done in a faster/more efficient way since it will potentially be processing large amounts of data to find what I want to return.
我知道它可以工作并产生我想要的结果,但是可以以更快/更有效的方式完成,因为它可能会处理大量数据以查找我想要返回的内容。
(ID in the example below is an auto-increment PK field) (以下示例中的ID是一个自动递增的PK字段)
select x, y, z
from table
where id = (select max(id) from table where z = someValue)
I would suggest: 我会建议:
select top (1) x, y, x
from table
where z = somevalue
order by id desc;
For performance, you want an index on (z, id)
. 为了提高性能,您需要在
(z, id)
上建立索引。
I like using a CTE for this, as you can do an INNER JOIN
with the source table and the CTE. 我喜欢为此使用CTE,因为您可以对源表和CTE进行
INNER JOIN
。
;WITH LookupCTE AS
(
select id = MAX(id)
FROM table
WHERE z = someValue
)
SELECT x, y, x
from table t1
INNER join LookupCTE t2 ON t1.id = t2.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.