Select IDs IN 多个值时的最新记录(即ORDER by)
Select the latest records (i.e. ORDER by) when IDs IN multiple values
比如devices
table这样的
id
user_id
last_used_at
1
111
2000-01-01 00:00:00
2
111
2003-01-01 00:00:00
3
222
2000-01-01 00:00:00
4
222
2003-01-01 00:00:00
select user_id = 111
最后使用的设备
SELECT *
FROM devices
WHERE user_id = 111
ORDER BY last_used_at DESC
LIMIT 1;
-- which should select device id = 2
select user_id IN (111, 222)
的所有设备
SELECT *
FROM devices
WHERE user_id IN (111, 222);
问题是 - 如何 select user_id 最后使用的设备 IN (111, 222)?
有多种方法可以做到这一点。使用 WINDOW 函数是其中之一 -
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY last_used_at DESC) RN
FROM devices)
WHERE user_id IN (111, 222)
AND RN = 1;
您可以为此使用特定于 PostgreSQL 的 DISTINCT ON
:
SELECT DISTINCT ON (user_id) *
FROM devices
ORDER BY user_id, last_used_at DESC
比如devices
table这样的
id | user_id | last_used_at |
---|---|---|
1 | 111 | 2000-01-01 00:00:00 |
2 | 111 | 2003-01-01 00:00:00 |
3 | 222 | 2000-01-01 00:00:00 |
4 | 222 | 2003-01-01 00:00:00 |
select
最后使用的设备user_id = 111
SELECT * FROM devices WHERE user_id = 111 ORDER BY last_used_at DESC LIMIT 1; -- which should select device id = 2
select
的所有设备user_id IN (111, 222)
SELECT * FROM devices WHERE user_id IN (111, 222);
问题是 - 如何 select user_id 最后使用的设备 IN (111, 222)?
有多种方法可以做到这一点。使用 WINDOW 函数是其中之一 -
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY last_used_at DESC) RN
FROM devices)
WHERE user_id IN (111, 222)
AND RN = 1;
您可以为此使用特定于 PostgreSQL 的 DISTINCT ON
:
SELECT DISTINCT ON (user_id) *
FROM devices
ORDER BY user_id, last_used_at DESC