如何解决mysql-基于表中列值最高的id连接表行-多个连接和条件
我在提出问题之前已经进行了搜索,并尝试了发现的问题-由于存在多个联接和条件,因此我参与了更多事务,并且无法获得正确的结果。
输入了基本数据的SQL Fiddle here。
下面的查询没有给出我想要的结果,但是给出了我要实现的目标的想法。我想为每个computer_id返回1个结果,其中time.capture_timestamp在特定的开始/结束值之间,并且是该表中包含该行其他列值的最高值。我在SO上尝试了一些涉及MAX()和子查询的不同操作,但似乎无法获得所需的内容。
SELECT
computers.computer_name,users.username,time.title,time.capture_timestamp
FROM computers
INNER JOIN time
ON time.computer_id = computers.computer_id AND time.capture_timestamp >= 0 AND time.capture_timestamp <= 9999999999
INNER JOIN users
ON users.user_id = time.user_id
GROUP BY computers.computer_id
ORDER BY time.capture_timestamp DESC
小提琴照原样返回:
computer_name username title capture_timestamp
computer1 user1 some title 1595524341
computer2 user3 some title3 1595524331
我想要的结果实际上是:
computer_name username title capture_timestamp
computer1 user2 some title2 1595524351
computer2 user3 some title3 1595524331
...根据小提琴中的示例值。是的,在此示例中,开始/结束时间值包括“所有内容”,但在使用中实际上会提供时间戳范围。
解决方法
使用ROW_NUMBER
:
WITH cte AS (
SELECT c.computer_name,u.username,t.title,t.capture_timestamp,ROW_NUMBER() OVER (PARTITION BY c.computer_id
ORDER BY t.capture_timestamp DESC) rn
FROM computers c
INNER JOIN time t ON t.computer_id = c.computer_id
INNER JOIN users u ON u.user_id = t.user_id
WHERE t.capture_timestamp BETWEEN 0 AND 9999999999
)
SELECT computer_name,username,title,capture_timestamp
FROM cte
WHERE rn = 1;
,
您可以添加相关的子查询以获得所需的结果
select
computers.computer_name,users.username,t.capture_timestamp
from computers
inner join time t
on t.computer_id = computers.computer_id
and t.capture_timestamp >= 0 and t.capture_timestamp <= 9999999999
inner join users
on users.user_id = t.user_id
where t.capture_timestamp =(
select max(capture_timestamp)
from time
where capture_timestamp >= 0 and capture_timestamp <= 9999999999
and t.computer_id = computer_id
)
order by t.capture_timestamp desc
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。