且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

选择最后n行而不使用order by子句

更新时间:2023-12-04 11:01:10

通过Lukas解决方案(截至2011年11月1日),您所期望的是真幸运。根据定义,RDBMS中没有自然顺序 。您依赖于实施细节,这些细节可能随新版本的发布而更改,恕不另行通知。否则转储/还原可能会更改该顺序。当数据库统计信息更改并且查询计划程序选择导致行顺序不同的其他计划时,它甚至可以突然更改

That you get what you expect with Lukas' solution (as of Nov. 1st, 2011) is pure luck. There is no "natural order" in an RDBMS by definition. You depend on implementation details that could change with a new release without notice. Or a dump / restore could change that order. It can even change out of the blue when db statistics change and the query planner chooses a different plan that leads to a different order of rows.

获取最后n个行的正确方法是具有一个时间戳或序列列,以及该列的 ORDER BY 。您可以想到的每个RDBMS都具有 ORDER BY ,因此它就像它的通用。

The proper way to get the "last n" rows is to have a timestamp or sequence column and ORDER BY that column. Every RDBMS you can think of has ORDER BY, so this is as 'generic' as it gets.

I 在此处引用该手册


如果未给出ORDER BY,则以
系统认为最快产生的顺序返回行。

If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce.

Lukas的解决方案可以避免 LIMIT ,这在各种RDBMS中的实现方式有所不同(例如,SQL Server使用 TOP n 而不是 LIMIT ),但是您需要订购

Lukas' solution is fine to avoid LIMIT, which is implemented differently in various RDBMS (for instance, SQL Server uses TOP n instead of LIMIT), but you need to ORDER BY in any case.

值得一提的是,尽管窗口函数是SQL标准的,但它们仍不如您通用不妨例如,MySQL不支持它们。

It may be worth mentioning that while window functions are in the SQL standard, they still aren't as generic as you might wish. MySQL, for instance, does not support them.