5

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?

Thank you all in advance.

Community
  • 1
  • 1
AleVale94
  • 727
  • 1
  • 8
  • 14
  • 2
    There is no such thing as an "even" or "odd" row in MySQL. Tables represent unordered sets. You need a column that specifies the ordering of the rows. – Gordon Linoff Sep 23 '14 at 11:30
  • 1
    if you have id's in order you can retrieve where id % 2==0 – Tushar Gupta Sep 23 '14 at 11:31
  • [http://stackoverflow.com/questions/15578727/select-every-second-row-mysql-without-auto-increment-or-data-of-table] – Anptk Sep 23 '14 at 11:40

2 Answers2

11

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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
5

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;
Ankit Bajpai
  • 13,128
  • 4
  • 25
  • 40