Ben*_*n M 7 mysql sql pagination
我有一个用 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
Run Code Online (Sandbox Code Playgroud)
我cursor使用的总是由所有三列组成。
我使用此查询来获取下一个结果(在 之后cursor):
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
Run Code Online (Sandbox Code Playgroud)
以及此查询之前的结果(在 之前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
Run Code Online (Sandbox Code Playgroud)
当使用上一个查询时cursor [id = dd, date = 2017-11-03, time = 21:45:00],它不会返回带有 的行id = d3,因为time是null,并且不会被 选中time < cursor.time。
尽管我尝试使用time < cursor.time OR time IS NULL而不是time < cursor.time包含带有null值的行。这似乎解决了这个特定问题,但随后又产生了一个新问题:当使用上一个查询时cursor [id = d3, date = 2017-11-03, time = null],因为现在结果包含所提供游标的行。
我希望有一个简单的解决方案。网络上似乎没有处理null光标分页中的值的示例或教程。
注意:null对于解决方案,在值之前或之后排序并不重要non-null,只要它一致即可。(MySQL的默认排序是null < non-null)
将另一列添加到表中。将其设为DATETIME. date当不为NULL时将and合并time进去;date当 NULL 时与某些特定时间结合。然后你的光标有两列可以使用并且没有空值。
如果您有最新版本的 MySQL,则可以使用“生成的存储”列,从而避免任何代码更改。
并且一定要有INDEX(datetime, id)。