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

查看:14
本文介绍了MAX vs Top 1 - 哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不检查一些代码,并遇到了一些人做过的事情,但想不出为什么我的方法更好,而且可能不是,那么,哪个更好/更安全/更有效?

SELECT MAX(a_date) FROM a_table WHERE a_primary_key = 5 GROUP BY event_id

SELECT TOP 1 a_date FROM a_table WHERE a_primary_key = 5 ORDER BY a_date

我会选择第二个选项,但我不确定为什么,如果这是对的.

解决方案

如果您的表已编入索引,则性能通常相似.

尽管值得考虑:Top 通常只有在您对结果进行排序时才有意义(否则,top什么?)

对结果进行排序需要更多处理.

Min 并不总是需要订购.(视情况而定,但通常您不需要 order by 或 group by 等)

在您的两个示例中,我希望 speed/x-plan 非常相似.您可以随时查看您的统计数据来确定,但我怀疑差异会很大.

I had to review some code, and came across something that someone did, and can't think of a reason why my way is better and it probably isn't, so, which is better/safer/more efficient?

SELECT MAX(a_date) FROM a_table WHERE a_primary_key = 5 GROUP BY event_id

OR

SELECT TOP 1 a_date FROM a_table WHERE a_primary_key = 5 ORDER BY a_date

I would have gone with the 2nd option, but I'm not sure why, and if that's right.

解决方案

Performance is generally similar, if your table is indexed.

Worth considering though: Top usually only makes sense if you're ordering your results (otherwise, top of what?)

Ordering a result requires more processing.

Min doesn't always require ordering. (Just depends, but often you don't need order by or group by, etc.)

In your two examples, I'd expect speed / x-plan to be very similar. You can always turn to your stats to make sure, but I doubt the difference would be significant.

这篇关于MAX vs Top 1 - 哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆