[英]How can I SELECT the last row in a MySQL table ? I don't have any auto increment key
I want to SELECT the last row in a MySQL table. 我想在MySQL表中选择最后一行。 I don't have any auto increment key in that table.
我在该表中没有任何自动增量键。
public String getLastLeaveId() {
try {
Statement stmt = getConnection();
String sql="select leaveID from applied leave"; // here I want some logic that will fetch only leave_id from last row only
stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//Table Structure --->
(leave_id varchar(50) primary key,emp_id varchar(40),birthday varchar(20),anniv varchar(20),rh varchar(200),total int,foriegn key(emp_id) reference employee);
降序排列在您现在要订购的任何列上,最后limit 0,1
。
There is no implicit ordering in a database table. 数据库表中没有隐式排序。 If you don't have an auto-increment column, a date/time column, or some other column that follows a natural order when you insert rows, you're limited to using some other way of faking it.
如果在插入行时没有自动递增的列,日期/时间列或其他遵循自然顺序的列,则只能使用其他伪造方法。
You don't show a table structure in your question, nor do you state whether you're using MyISAM or InnoDB. 您没有在问题中显示表结构,也没有说明您使用的是MyISAM还是InnoDB。 MyISAM stores rows in order they're inserted (usually) so you can use something inneficient like
ResultSet.last()
from Java to get the last row, but if you're not using MyISAM you can't depend on that. MyISAM按通常的顺序存储行,因此您可以使用Java中的
ResultSet.last()
类的无效函数来获取最后一行,但是如果您不使用MyISAM,则不能依赖于此。 InnoDB, the default storage engine, stores records in a more efficient B-Tree order, and does not retain the insert order at all, but rather stores records according to the primary key's order. InnoDB是默认的存储引擎,它以更高效的B树顺序存储记录,并且根本不保留插入顺序,而是根据主键的顺序存储记录。
In short, you'll need to pick a field that has some natural order (or invent one) and order by that. 简而言之,您需要选择一个具有自然顺序(或发明一个自然顺序)的字段,并以此顺序进行排序。
it's may be useful 这可能有用
SELECT MAX(ID) FROM YourTable
// Similarly, ORDER BY with LIMIT:
SELECT ID FROM YourTable ORDER BY ID Desc Limit 1
Without having either a where clause and/or order by condition you can't fetch the last row in a query directly. 如果没有条件子句和/或条件,您将无法直接获取查询的最后一行。 You need to traverse through all the rows to stop before last row.
您需要遍历所有行才能在最后一行之前停止。
Only positive options I see are: 我看到的唯一积极选择是:
rs.last()
and then read it. rs.last()
然后读取它。 order by desc
clause based on a column. order by desc
子句。 row_num
on all selected rows and run a select with desc order on that row_num. row_num
,并在该row_num上以desc顺序运行选择。 Pseudo example on 4th option above: 上面第4个选项的伪示例:
这就是你想要的。
SELECT * FROM table_name ORDER BY id DESC LIMIT 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.