SQL-选择唯一的行且时间超过4小时

时间:2019-03-24 02:21:13

标签: sql

我试图选择所有超过4小时的行,仅选择唯一的行,并将其限制为250行。

我的数据库如下:

id | titleid | version | timestamp
1  | TEST1   | 1.00    | 2019-03-23 02:40:33
2  | TEST1   | 1.01    | 2019-03-23 02:40:33
3  | TEST1   | 1.02    | 2019-03-23 02:40:33
4  | TEST2   | 1.50    | 2019-03-23 02:40:33
5  | TEST2   | 1.51    | 2019-03-23 02:40:33

我有这个查询:

SELECT m1.*
FROM patch_queue m1
LEFT JOIN patch_queue m2 ON (m1.titleid = m2.titleid AND m1.id < m2.id)
WHERE timestamp <= DATE_SUB(NOW(), INTERVAL 4 HOUR) AND m2.id IS NULL
LIMIT 250

哪个可以解决问题。我只是不确定如何将其组合为一个。它抛出:

  

where子句中的“时间戳”列不明确

有人碰巧知道我该怎么做吗?

所需结果:

id | titleid | version | timestamp // they're all older than 4 hours in this case
3  | TEST1   | 1.02    | 2019-03-23 02:40:33
5  | TEST2   | 1.51    | 2019-03-23 02:40:33

2 个答案:

答案 0 :(得分:0)

我假设您希望每titleid行,其中titleid在过去4小时内没有记录:

select t.*
from t
where t.timestamp = (select max(t2.timestamp)
                     from t t2
                     where t2.titleid = t.titleid
                    ) and
      t.timestamp < now() - interval 4 hour
order by timestamp desc
limit 250;

答案 1 :(得分:0)

您只需要指定m1.timestamp

SELECT m1.*
FROM patch_queue m1
LEFT JOIN patch_queue m2 ON (m1.titleid = m2.titleid AND m1.id < m2.id)
WHERE m1.timestamp <= DATE_SUB(NOW(), INTERVAL 4 HOUR) AND m2.id IS NULL
LIMIT 250

输出:

id  titleid version timestamp
3   TEST1   1.02    2019-03-23 02:40:33
5   TEST2   1.51    2019-03-23 02:40:33

Demo on dbfiddle