SQL 在最后数据的语句中

SQL in statement for last data

我对 IN 语句有疑问。我有两张桌子。

Table_1

id    | active_device_id| device_status
0     |  1              | 1
1     |  2              | 1
2     |  3              | 1

Table_2

id | device_id | value
0  |          1| 10
1  |          2| 20
2  |          3| 30
3  |          1| 40
4  |          2| 50
5  |          5| 60

我想根据 Table_1

从 Table_2 获取设备的最后一个值

所以我用这个

select * 
from Table_2
where device_id in (
    select active_device_id
    from Table_1
    where device_status=1
 )
 order by id desc

此查询获取设备的所有记录。但我想为每台设备获取最后一条记录。很快我想要这个

id | device_id| value
4  |         2| 50
3  |         1| 40
2  |         3| 30

你能帮我解决这个问题吗?

使用 IN 语句将 return 该值匹配的所有记录,这将最终 returning 来自 Table_2 的所有值,除了 id= 5 个(device_id 个,共 5 个不在 Table_1 中)。此外,使用 IN 语句的方式最好使用 INNER JOIN.

完成您所追求的目标的更好方法是使用自联接。基本上,我将 Table_2 连接回自身,并且只 return 为匹配 device_id.[= 的每一行 table 中的最高 "id" 值14=]

SELECT t2.*
FROM Table_2 AS t2
INNER JOIN Table_1 AS t1 ON t2.device_id = t1.active_device_id
  AND t1.device_status = 1
LEFT JOIN Table_2 AS t2self ON t2.device_id=t2self.device_id AND t2self.id>t2.id
WHERE t2self.id IS NULL
ORDER BY t2.id DESC

如果您的 DBMS 支持 window 函数(顺便说一下,它应该支持),则有一个稍微简单的方法:

select id, device_id, value from 
(
select row_number() over (partition by t2.device_id order by t2.id desc) as rownum,
t2.*
from table_2 t2 join table_1 t1 on t2.device_id = t1.active_device_id and t1.device_status = 1
) temp where rownum = 1

但是,我赞成 Ashley Lee 的回答,因为我认为它为其他 DBMS MySql 提供了非常重要的 ANSI-SQL 解决方法,这里习惯用变量来达到同样的效果。