即使 table 包含一条记录,也获取最后一条记录

Get the last record even when the table contains one record

我正在尝试使用准备好的语句获取 table 中的最后一条记录。我已经尝试了下面的两个查询,但是当 table 只包含一条记录时,我在获取它时遇到了问题。

我单独执行查询时得到结果,但是当我在 preparedStatement 中执行它时,没有进入 while 循环。即使 table 包含一条带有准备语句的记录,我如何获取最后一条记录?

感谢任何帮助。

第一次查询:

select stop_name 
from behaviour 
where mac = ? 
order by behaviour_id desc 
limit 1

第二次查询:

select stop_name 
from behaviour 
where created_at in (select max(created_at) from behaviour) 
  and mac = ?

Table:

CREATE TABLE IF NOT EXISTS behaviour(
                           behaviour_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                           mac VARCHAR(30) NOT NULL,
                           stop_name VARCHAR(30) NOT NULL,
                           stop_distance INT(11) NOT NULL, 
                           speed INT(11) NOT NULL,
                           created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)

代码

String sql = "select stop_name from behaviour where mac = ? order by behaviour_id desc limit 1";
//String sql = "select stop_name from behaviour where created_at in (select max(created_at) from behaviour) and mac = ?";
PreparedStatement preparedLastStopName = con.prepareStatement(sql);
preparedLastStopName.setString(1, macD);

ResultSet rsLastStopName = preparedLastStopName.executeQuery();

String sto_nam = "";

while (rsLastStopName.next()) {
    sto_nam = rsLastStopName.getString("stop_name");
}

select 前 1 * 来自 mytable order by insert_date desc