可能重复:
SQL Query with MySQL
我在Java中使用Jersey实现了Rest Web Service(JAX-RS)。我使用hibernate从MySQL数据库中获取数据。 有了这个查询:
(Select distinct deliverable.id from Task as t where t.project.id= :id And t.user.username = :name order by t.id desc")
.setMaxResults(3)
.setLong("id", projectId)
.setString("name", username)
.list();
我的结果是正确的:[275,51,286]。这是数据库中每个id的提供密钥:
id key
---------------------
275 2.0
51 cm
286 19.87
现在我使用这个查询(Everything是相同的,除了deliverrable.key而不是deliverrable.id):
(Select distinct deliverable.key from Task as t where t.project.id= :id And t.user.username = :name order by t.id desc")
.setMaxResults(3)
.setLong("id", projectId)
.setString("name", username)
.list();
结果是:[“2.0”,“19.88”,“19.99”]。第一个是正确的,但第二个和第三个是完全不同的键。
也许它可以通过“别名”或任何其他方式解决。你的建议?
答案 0 :(得分:0)
我找到了答案:
("select d.key from Deliverable as d, Task as t
where t.deliverable.id = d.id and
t.id = (select max(t1.id) from Task t1 where t1.deliverable.id = d.id)
and d.project.id= :id
and t.user.username = :name
order by t.id desc")
.setMaxResults(3)
.setLong("id", projectId)
.setString("name", username)
.list();