gpt4 book ai didi

java - SQL Jpa,从组中选择最后一行

转载 作者:行者123 更新时间:2023-11-30 05:50:59 26 4
gpt4 key购买 nike

我需要返回表位置中每个设备的最后一行

我的表名是:位置

+------------+----------+--------------+--------------+----------+  
| locationId | deviceId | dataRegistro | horaRegistro | location |
+------------+----------+--------------+--------------+----------+
| 50 | 1 | 2012-11-07 | 15:35:00 | A12 |
+------------+----------+--------------+--------------+----------+
| 51 | 1 | 2012-11-07 | 15:37:40 | B2 |
+------------+----------+--------------+--------------+----------+
| 52 | 2 | 2012-11-07 | 15:35:12 | B8 |
+------------+----------+--------------+--------------+----------+
| 53 | 2 | 2012-11-07 | 15:35:40 | 50C |
+------------+----------+--------------+--------------+----------+
| 54 | 2 | 2012-11-07 | 15:40:00 | 94A |
+------------+----------+--------------+--------------+----------+

从我做的一台设备中选择最后一行

从 Location L 中选择 L,其中 deviceId = :deviceId order by "dataRegistro"DESC, "horaRegistro"DESC limit 1

现在如何选择每个设备的所有最新位置? :( 我使用 Java JPA。

谢谢,

埃文德罗

最佳答案

如果 ID 是有序的,那么稍后记录的记录对应于较晚的日期,您可以使用此查询(我不会费心将字符串转换为日期,这会使它慢于可接受的速度。):

select L from Location L where deviceId = :deviceId order by L.locationId DESC 

并限制在 Java 代码中返回的行数:

//EntityManager em; defined earlier
Query q = em.createQuery("select L from Location L where deviceId = :deviceId order by L.locationId DESC ");
q.setParameter("deviceId", "theDeviceIdIWantToQuery");
q.setMaxResults(1);
List<Location> results=query.getResultList();

如果给定的 deviceId 没有行,这将是一个空列表,或者列表包含 1 个位置项 - 最后一个。

如果你想一次选择所有设备的最新位置,你可以使用一个 IN 子句和一个子查询:

select L2 FROM Location L2 WHERE L2.locationId IN
(select L.locationId from Location L
where L.deviceId = :deviceId
order by L.locationId DESC
group by L.deviceId)

可悲的是,JPQL doesn't permit using subqueries in the FROM clause ,所以虽然我会选择这样做,但只能通过使用 native 查询功能来实现,这使用起来要方便得多。

顺便说一句,在我看来,像您这样存储时间戳是一种不好的做法。它不能正确索引,在查询和排序时会带来麻烦,简直就是一场噩梦。我会认真地重新考虑您架构的这一部分。

关于java - SQL Jpa,从组中选择最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13289553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com