简体   繁体   English

这两个 sql 语句(JDBC)有什么区别?

[英]What is the difference between these two sql statements(JDBC)?

I want to get last id in table.我想得到表中的最后一个 id。 First I did this:首先我这样做:

String selectId = "SELECT MAX(id) FROM book_store.cart" ;    
PreparedStatement ps = conn.prepareStatement(selectId);  
rs =  ps.executeQuery();
while(rs.next()){
    autoIncKey = rs.getInt("id");
}

Here I get error "column id not not found" .在这里我收到错误“未找到列 ID”

Then I changed the query to this, which is working:然后我将查询更改为这个,它正在工作:

String selectId = "SELECT id FROM book_store.cart ORDER BY id DESC LIMIT 1";

I am wondering why the first query is giving me an error and second does not if they are returning the same value?我想知道为什么第一个查询给了我一个错误,而第二个查询却没有返回相同的值?

The first query will return a row with a column name of MAX(id) .第一个查询将返回列名为MAX(id)的行。

Not the most useful name for a column, so change the query to set an alias for that column like this不是最有用的列名称,因此更改查询以像这样为该列设置别名

SELECT MAX(id) id FROM book_store.cart

And now the column will be called id and the rs.getInt("id") will work现在该列将被称为id并且rs.getInt("id")将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM