简体   繁体   English

SQL:MAX与SELECT TOP 1

[英]SQL: MAX versus SELECT TOP 1

I'm not very expert with SQL, so pardon me for the newbie question. 我对SQL不是很熟练,所以请原谅我的新手问题。 Also for my basic english. 也为我的基本英语。

I need to extract from a table the value of the row(s) with the maximum date. 我需要从表中提取具有最大日期的行的值。 The problem is that I can only select some rows, and the conditions would consider also other tables, so to get the right rows I have to do some joins with these other tables. 问题是我只能选择一些行,而且条件还会考虑其他表,因此要获得正确的行,我必须与其他表进行一些连接。

Normally (using just one table), to resolve this problem I use an SQL statement like this one: 正常情况下(仅使用一个表),要解决此问题,我使用如下所示的SQL语句:

SELECT t1.value
FROM table t1
INNER JOIN (SELECT MAX(date) as maxDate
    FROM table
    WHERE field=3) t2
ON t1.date=t2.maxDate
WHERE t1.field=3

Now, in the case I am speaking of, I would need to do something like: 现在,就我而言,我将需要执行以下操作:

SELECT t1.value
FROM table t1
INNER JOIN otherTable o1 ON o1.key=t1.oKey
INNER JOIN (SELECT MAX(date) as maxDate
    FROM table t2
    INNER JOIN otherTable o2 ON o2.key=t2.oKey
    WHERE t2.field=3 and o2.oField=10) t3
ON t1.date=t3.maxDate
WHERE t1.field=3 and o1.oField=10

But this solution seems inefficient to me, because I have to "duplicate" all the joins, and the joins conditions. 但是这种解决方案对我来说似乎效率不高,因为我必须“复制”所有联接和联接条件。

Is there any other way to do this? 还有其他方法吗? I don't need to extract all the results (could be more than one), so I thought also at this solution: 我不需要提取所有结果(可能不止一个),因此我也认为这种解决方案:

SELECT TOP 1 t.value
FROM table t
INNER JOIN otherTable o ON o.key=t.oKey
WHERE t.field=3 and o.oField=10
ORDER BY t.date DESC

But I am not sure if the result will be correct: does it first sort the results and then select the top 1? 但是我不确定结果是否正确:是否先对结果进行排序,然后选择前1个? In other words: can I be sure that the row is the one with the max date? 换句话说:我可以确定该行是具有最大日期的行吗?

Also, is the second method actually more efficient? 另外,第二种方法实际上更有效吗?

Thank you guys!! 感谢大伙们!!

The difference between MAX and TOP 1 was also discussed on these posts: 这些帖子还讨论了MAX和TOP 1之间的区别:

MAX vs Top 1 - which is better? MAX vs Top 1-哪个更好?

SQL performance MAX() SQL性能MAX()

To answer your question, select top 1 and max are not the same thing. 要回答您的问题,请select top 1max不是同一回事。 Select top 1 will return you first row of result set, it doesn't matter what date/data is in that row. Select top 1将返回结果集的第一行,而该行中的日期/数据无关紧要。

If you use select top 1 date from table order by date desc you will get the max date, so no worry there. 如果使用select top 1 date from table order by date desc则会获得max日期,因此不必担心。

Select max(date) will always give you the highest date, or to be precise the last date. Select max(date)将始终为您提供最高日期,或者准确地说是最后日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM