MySQL:如何从表中选择除最后一行之外的所有行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/315621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:25:55  来源:igfitidea点击:

MySQL: How to select all rows from a table EXCEPT the last one

mysqlselectlimits

提问by Lasse A Karlsen

I have a table with N rows, and I wanna select N-1 rows.

我有一个有 N 行的表,我想选择 N-1 行。

Suggestions on how to do this in one query, if it's possible..?

关于如何在一个查询中执行此操作的建议(如果可能)?

回答by Joshua Carmody

Does the last row have the highest ID? If so, I think this would work:

最后一行的 ID 是否最高?如果是这样,我认为这会起作用:

SELECT * FROM TABLE WHERE ID != (SELECT MAX(ID) FROM TABLE)

MySQL does allow subselects in the current version, right?

MySQL 确实允许在当前版本中进行子选择,对吗?

However, in most cases, it'd probably perform better if you selected all the rows and then filtered the unwanted data out in your application.

但是,在大多数情况下,如果您选择所有行,然后在应用程序中过滤掉不需要的数据,它的性能可能会更好。

回答by dkretz

SELECT DISTINCT t1.columns FROM table t1
INNER JOIN table t2 ON t1.id < t2.id

SELECT DISTINCT t1.columns FROM table t1
INNER JOIN table t2 ON t1.id < t2.id

In my experience, MySQL loves this technique, going back several versions.

根据我的经验,MySQL 喜欢这种技术,可以追溯到几个版本。

回答by Redithion

Another technique I don't see listed here is

我没有看到这里列出的另一种技术是

SELECT * FROM table ORDER BY id DESC LIMIT 10000 OFFSET 1;

This will give you the records ordered by id descendant except first, that is except the last in the original order.
Note that with this method you will only take 10000 records, however this number can be as high as you want but cannot be omitted.
The advantageof this method is that you can order by whatever you want.
The disadvantageis that it gives you the records ordered from last to first.
Finally it worths noting that the other methods here works quite well

这将为您提供按 id 后代排序的记录,除了第一个,即原始顺序中的最后一个。
请注意,使用此方法,您将只获取 10000 条记录,但此数字可以随您的需要而增加,但不能省略。这种方法
的优点是您可以随意订购。
缺点是它为您提供了从最后到第一次排序的记录。
最后值得注意的是,这里的其他方法效果很好

回答by Devansh Modi

Another way to do this could be:

另一种方法可以是:

SELECT * FROM table WHERE ID <> LAST_INSERT_ID()

Reference: http://dev.mysql.com/doc/refman/5.7/en/getting-unique-id.html

参考:http: //dev.mysql.com/doc/refman/5.7/en/getting-unique-id.html