【发布时间】:2021-10-28 11:20:52
【问题描述】:
我有一个用 MySQL(8.0 版)实现的游标分页,只要不涉及 null 值,它就可以正常工作。
这是我的示例数据(id 是随机 UUID,date 是日期,time 是时间):
id | date | time
--------------------------
68 | 2017-10-28 | 22:00:00
d3 | 2017-11-03 | null
dd | 2017-11-03 | 21:45:00
62 | 2017-11-04 | 14:00:00
a1 | 2017-11-04 | 19:40:00
我使用的cursor 总是包含所有三列。
我使用这个查询来获得下一个结果(在cursor之后):
SELECT * FROM table
WHERE (date > cursor.date)
OR (date = cursor.date AND time > cursor.time)
OR (date = cursor.date AND time = cursor.time AND id > cursor.id)
ORDER BY date ASC, time ASC, id ASC
这个查询prev结果(在cursor之前):
SELECT * FROM table
WHERE (date < cursor.date)
OR (date = cursor.date AND time < cursor.time)
OR (date = cursor.date AND time = cursor.time AND id < cursor.id)
ORDER BY date DESC, time DESC, id DESC
当使用带有cursor [id = dd, date = 2017-11-03, time = 21:45:00] 的prev 查询时,它不会返回带有id = d3 的行,因为time 是null,而这不会被@987654335 选中@。
虽然我尝试使用time < cursor.time OR time IS NULL 而不是time < cursor.time 来包含具有null 值的行。这似乎解决了这个特殊问题,但随后又产生了一个新问题:当使用带有cursor [id = d3, date = 2017-11-03, time = null] 的 prev 查询时,因为现在结果包含所提供游标的行。
我希望有一个简单的解决方案。网络上似乎没有处理光标分页中null 值的示例或教程。
注意:对于解决方案,null 是否在 non-null 值之前或之后排序并不重要,只要它是一致的。 (MySQL的默认排序是null < non-null)
【问题讨论】:
-
请注明您使用的 MySQL 版本。
-
@KaziMohammadAliNur 我正在运行 MySQL 8.0.26
-
感谢@Benjamin M 如此快速的回复。我试图用 cte 和 row_number() 找到解决方案。
-
如果我的评论很幼稚,我很抱歉,但是在您的查询中不能使用
time < cursor.time OR time IS NULL OR cursor.time IS NULL吗?我对游标不太满意,但我不知道为什么它不起作用。 -
@Christophe 无需抱歉。我们都在这里学习新事物。你的想法行不通:正如我在问题中所说,我尝试使用已经选择了太多行的
time < cursor.time OR time IS NULL。当您现在添加另一个OR条件时,您不会缩小结果范围,而是可能选择更多行。
标签: mysql sql pagination