在 MySQL 中只选择偶数/奇数行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25993936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select only even/odd rows in MySQL
提问by AleVale94
I'm trying to select all even or odd rows from a table in MySQL without using the ID field. I tried this, but I suppose that it doesn't work since it's based on SQL Server: how to show only even or odd rows in sql server 2008?
我试图在不使用 ID 字段的情况下从 MySQL 的表中选择所有偶数或奇数行。我试过了,但我认为它不起作用,因为它基于 SQL Server: 如何在 sql server 2008 中仅显示偶数或奇数行?
Thank you all in advance.
谢谢大家。
回答by Gordon Linoff
Assuming you have a column that specifies the ordering of the table, then you can use variables to do what you want:
假设您有一列指定表的顺序,那么您可以使用变量来执行您想要的操作:
select t.*
from (select t.*, (@rn := @rn + 1) as seqnum
from table t cross join
(select @rn := 0) vars
order by col
) t
where mod(seqnum, 2) = 0;
回答by Ankit Bajpai
Try to use this:-
尝试使用这个:-
SELECT cols
FROM (
SELECT cols, @rowNumber := @rowNumber+ 1 rn
FROM YourTable
JOIN (SELECT @rowNumber:= 0) r
) t
WHERE rn % 2 = 1;