SQL 从列开始
SQL Starting with columns
我有:
Id | Timestamp column
---------------------------
1 | 700 (not ten, but simple to read)
2 | 800
3 | 800
4 | 800
5 | 600
我得到前 2 条记录,按时间戳 DESC 排序
Id | Timestamp column
---------------------------
2 | 800
3 | 800
现在,我无法获得按时间戳 DESC 排序的下 2 条记录,从 id 3 开始,时间戳为 800
我试试:
SELECT * FROM table WHERE timestamp < 800 ORDER BY timestamp DESC LIMIT 2
但是returns Id 1 和 5,这是不正确的。
也试试看:
SELECT * FROM table WHERE timestamp <= 800 ORDER BY timestamp DESC LIMIT 2
但是 returns id 2 和 3,这又是不正确的。
也试试
SELECT * FROM table WHERE timestamp <= 800 AND id > 3 ORDER BY timestamp DESC LIMIT 2
但是 returns Id 4 和 5,这又是不正确的。
等等....我都试过了。
查询应该 return 正好:
Id | Timestamp column
---------------------------
4 | 800
1 | 700
我也尝试使用 order by id,但无法正常工作。
有帮助吗?
编辑:我无法解释,但可以肯定的是我不知道已经提取了多少条记录,所以我不能使用 Offset。我只知道最后一条记录 - id 3 和时间戳 800...
您需要同时按 timestamp
和 id
进行排序,以便在具有相同 timestamp
的所有行中获得一致的排序。然后当你进行下一个查询时,你使用最后一个 id
作为 WHERE
子句的一部分。
所以第一次是
SELECT *
FROM table
ORDER BY timestamp DESC, id
LIMIT 2
将此最后一行的 ID 和时间戳获取到 @id
和 @timestamp
,那么您的下一个查询应该是:
SELECT *
FROM table
WHERE (timestamp = @timestamp AND id > @id) OR (timestamp < @timestamp)
ORDER BY timestamp DESC, id
LIMIT 2
使用下面的查询
Select *
from table
where not exists (select * from table where id<=3 and timestamp= 800)
order by id asc, timestamp desc
limit 2
我有:
Id | Timestamp column
---------------------------
1 | 700 (not ten, but simple to read)
2 | 800
3 | 800
4 | 800
5 | 600
我得到前 2 条记录,按时间戳 DESC 排序
Id | Timestamp column
---------------------------
2 | 800
3 | 800
现在,我无法获得按时间戳 DESC 排序的下 2 条记录,从 id 3 开始,时间戳为 800
我试试:
SELECT * FROM table WHERE timestamp < 800 ORDER BY timestamp DESC LIMIT 2
但是returns Id 1 和 5,这是不正确的。
也试试看:
SELECT * FROM table WHERE timestamp <= 800 ORDER BY timestamp DESC LIMIT 2
但是 returns id 2 和 3,这又是不正确的。
也试试
SELECT * FROM table WHERE timestamp <= 800 AND id > 3 ORDER BY timestamp DESC LIMIT 2
但是 returns Id 4 和 5,这又是不正确的。
等等....我都试过了。
查询应该 return 正好:
Id | Timestamp column
---------------------------
4 | 800
1 | 700
我也尝试使用 order by id,但无法正常工作。
有帮助吗?
编辑:我无法解释,但可以肯定的是我不知道已经提取了多少条记录,所以我不能使用 Offset。我只知道最后一条记录 - id 3 和时间戳 800...
您需要同时按 timestamp
和 id
进行排序,以便在具有相同 timestamp
的所有行中获得一致的排序。然后当你进行下一个查询时,你使用最后一个 id
作为 WHERE
子句的一部分。
所以第一次是
SELECT *
FROM table
ORDER BY timestamp DESC, id
LIMIT 2
将此最后一行的 ID 和时间戳获取到 @id
和 @timestamp
,那么您的下一个查询应该是:
SELECT *
FROM table
WHERE (timestamp = @timestamp AND id > @id) OR (timestamp < @timestamp)
ORDER BY timestamp DESC, id
LIMIT 2
使用下面的查询
Select *
from table
where not exists (select * from table where id<=3 and timestamp= 800)
order by id asc, timestamp desc
limit 2