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

左心房为你撑大大i 提交于 2019-11-28 00:12:30

问题


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

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


回答1:


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

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

MySQL does allow subselects in the current version, right?

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.




回答2:


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.




回答3:


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 advantage of this method is that you can order by whatever you want.
The disadvantage is that it gives you the records ordered from last to first.
Finally it worths noting that the other methods here works quite well




回答4:


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



来源:https://stackoverflow.com/questions/315621/mysql-how-to-select-all-rows-from-a-table-except-the-last-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!