gpt4 book ai didi

MySQL:基于列搜索,另一列中的每个唯一值和最大时间

转载 作者:可可西里 更新时间:2023-11-01 08:27:15 26 4
gpt4 key购买 nike

我正在努力组装正确的 MySQL 语句,很想听听堆栈交换社区的一些意见。

我有一个这样的表:

id | controller | sensor | data | time
1 | A | TEMP | 65 | 12:30
2 | A | SWITCH | 0 | 12:30
3 | A | TEMP | 66 | 12:31
4 | A | SWITCH | 1 | 12:31
5 | B | SWITCH | 1 | 12:31
6 | A | TEMP | 67 | 12:32
7 | A | SWITCH | 1 | 12:32
8 | B | SWITCH | 65 | 12:32
9 | A | TEMP | 68 | 12:33
10 | B | TEMP | 65 | 12:33
11 | A | SWITCH | 0 | 12:33
12 | B | TEMP | 65 | 12:34
13 | A | HUMID | 10 | 12:35
14 | B | HUMID | 10 | 12:35

我真正想做的是从给定 Controller 中为每个传感器选择具有 MAX(time) 的所有行。因此,如果我想要 Controller A,则此表上的结果将是:

9  | A          | TEMP   | 68   | 12:33
11 | A | SWITCH | 0 | 12:33
13 | A | HUMID | 10 | 12:35

对于给定 Controller ,每个传感器具有最长时间的项目。

到目前为止最好的陈述是:

SELECT * FROM table WHERE time = (SELECT MAX(time) FROM table WHERE sensor = "TEMP"和 controller = "A")

但我只能用这个(很明显)得到一个传感器,而且我不确定如何才能得到我正在寻找的东西。我几乎需要类似 for 循环的东西来遍历每个 sensor = * 和 controller = A 以找到最长时间,但我不知道如何实现它。非常感谢您的反馈。

感谢阅读,

最佳答案

一种选择是使用子查询将表连接回到自身:

select y.id, y.controller, y.sensor, y.data, y.time
from yourtable y join (
select controller, sensor, max(time) maxtime
from yourtable
group by controller, sensor
) t on y.controller = t.controller and
y.sensor = t.sensor and
y.time = t.maxtime
where y.controller = 'A'

关于MySQL:基于列搜索,另一列中的每个唯一值和最大时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34270200/

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