gpt4 book ai didi

mysql - SQL 在存在重复项时查找最接近的时间戳

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:11 25 4
gpt4 key购买 nike

我找不到我的问题的主题,所以我在这里问。我有选择:

  SELECT t1.*, 
t2.unixtimestamp as rj_time,
t2.response_detail as rj_error
FROM t1
LEFT JOIN table2 as t2
ON t1.id=t2.personid
AND t1.clientcode=t2.client
WHERE t1.clientcode='quouk'
AND (t1.language = 'en_GB')
ORDER BY t1.id

表 1:

id     clientcode     language     
1 quouk en_GB
2 quouk en_GB
3 quouk en_GB

表 2:

id     personid     client     language     unixtimestamp     response_detail     
1 1 quouk en_GB 1393401000 error
2 1 quouk en_GB 1393401001 error
3 2 quouk en_GB 1393404600 error
4 2 quouk en_GB 1393404601 error
5 3 quouk en_GB 1393257900 error
6 3 quouk en_GB 1393257901 error

因此,如果我启动此查询,它会返回 6 行,但结果应该是 3 行(来自表 2:2、4、6 id)。如果您查看时间戳,您会发现行之间存在细微差别。这意味着我需要找到离现在最近的日期。我看到很多在查询末尾使用 LIMIT 的解决方案,但我认为它在我的情况下有点不同。

最佳答案

假设时间戳不是 future 的,那么离现在最近的就是最新的。

因此,您可以通过针对子查询添加一个简单的 LEFT JOIN 来做到这一点:-

SELECT t1.*, t2.unixtimestamp as rj_time, t2.response_detail as rj_error 
FROM t1
LEFT OUTER JOIN
(
SELECT personid, client, MAX(unixtimestamp) AS MaxTimeStamp
FROM table2
GROUP BY personid, clientcode
) Sub1
ON t1.id = Sub1.personid AND t1.clientcode = Sub1.client
LEFT OUTER JOIN table2 as t2
ON Sub1.personid=t2.personid AND Sub1.client = t2.client AND Sub1.MaxTimeStamp = t2.unixtimestamp
WHERE t1.clientcode='quouk'
AND (t1.language = 'en_GB')
ORDER BY t1.id

这会从 table2 中获取每个人/客户的最新时间戳,然后将其与 table2 结合以获取所需的其他列(即 response_detail)。如果您只是使用 MAX,那么您可能无法获得 response_detail 的正确值,因为该值来自未定义的行,而不是来自 MAX 适用的行。

关于mysql - SQL 在存在重复项时查找最接近的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22040388/

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