[英]Get the most recent records on date and id field mySql
我有一张这样的桌子:
+--------+--------+------+----------+----+----+
| id | id2 | id3 | date |at1 | at2|
+--------+--------+------+----------+----+----+
| 111 | | | 5/12/19 | a | |
| 111 | 10 | | 2/12/19 | b | j |
| 111 | 10 | 45 | 2/12/19 | f | |
| 111 | 10 | 45 | 3/12/19 | c | |
| 222 | 1010 | | 5/12/19 | | e |
| 222 | 1010 | 56 | 1/12/19 |a | d |
| 33 | 1010 | 56 | 5/12/19 | | c |
+---------------------------------------------+
我想根据date
和id
检索最新记录,并只公开具有组合id
和( id2
或id3
)的行。 在我提供的表格中,结果应该是这样的:
+--------+--------+------+----------+----+----+
| id | id2 | id3 | date |at1 | at2|
+--------+--------+------+----------+----+----+
| 111 | 10 | | 2/12/19 | b | j |
| 111 | 10 | 45 | 3/12/19 | c | a |
| 222 | 1010 | | 5/12/19 |a | e |
| 222 | 1010 | 56 | 1/12/19 |a | e |
| 33 | 1010 | 56 | 5/12/19 | | c |
+---------------------------------------------+
我尝试使用此查询(来自另一个问题)来实现它,但我没有管理,因为我对 sql 不太熟悉:
select t.id, t.id2, t.id3, t.date,
coalesce(t.at1, g.at1) at1, coalesce(t.at2, g.at2) at2
from tab t inner join (
select id, id2, id3,
max(date) date, max(at1) at1, max(at2) at2
from tab
group by id2, id3
) g on g.pm = t.pm and g.pm2 <=> t.pm2 and g.pm3 <=> t.pm3 and g.date = t.date
先感谢您。
您可以使用 EXISTS 查询,但必须正确处理 NULL:
SELECT *
FROM t
WHERE NOT EXISTS (
SELECT 1
FROM t AS x
WHERE x.id <=> t.id
AND x.id2 <=> t.id2
AND x.id3 <=> t.id3
AND x.date > t.date -- row has a newer date
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.