Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想知道如何才能从表中只获取每隔一行。
我试过了 :
SELECT * FROM table_name ORDER BY id DESC LIMIT 1, 1
但当然我只得到第二行而不是 2, 4, 6, ...
有解决方案吗?
预先感谢您的帮助。
您可以使用用户变量的一个偷偷摸摸的技巧:
SELECT * FROM table_name, (SELECT @c := 0) t WHERE (@c := @c + 1) % 2 = 0 ORDER BY id DESC;
这是有效的,因为@c是为每一行(在WHERE子句中)计算的,我们只通过 mod 运算符选择偶数记录(2、4、6、...)%。
@c
WHERE
%
如果您想要奇数记录(1、3、5、...),请将其更改...% 2 = 0为...% 2 = 1.
...% 2 = 0
...% 2 = 1
更简单的版本
SELECT * FROM table_name WHERE MOD(id,2) = 0 ORDER BY id DESC
SQLFiddle
奇数将 0 改为 1