select every other row in MySQL without depending on any ID?

拥有回忆 提交于 2019-11-29 07:46:21

In unique MySQL fashion:

select  *
from    (
        select  *
        ,       @rn := @rn + 1 as rn
        from    Table1
        join    (select @rn := 0) i
        ) s
where   rn mod 2 = 0 -- Use = 1 for the other set

Example at SQL Fiddle.

This should work for MySQL:

SELECT col1, col2
FROM (
   SELECT col1, col2, @rowNumber:=@rowNumber+ 1 rn
   FROM YourTable
      JOIN (SELECT @rowNumber:= 0) r
) t 
WHERE rn % 2 = 1

This uses % which is the MOD operator.

And here is the sample fiddle: http://sqlfiddle.com/#!2/cd31b/2

Syddraf

Try this. I've adapted it from the answer linked below. I tested it on SQLFiddle and it appears to work.

http://sqlfiddle.com/#!2/0bccf/28
http://sqlfiddle.com/#!2/0bccf/29

Odd Rows:

SELECT x.*
FROM (
     SELECT @rownum:=@rownum+1 rownum, t.*
     FROM (SELECT @rownum:=0) r, table t
) x
WHERE MOD(x.rownum, 2) = 1

Even Rows:

SELECT x.*
FROM (
     SELECT @rownum:=@rownum+1 rownum, t.*
     FROM (SELECT @rownum:=0) r, table t
) x
WHERE MOD(x.rownum, 2) = 0

Adapted from: MySQL row number

hbhakhra

Consider this related answer: how to show only even or odd rows in sql server 2008?

It seems to be doing exactly what you want. I think this work in MySql, but of that I am not sure.

doesn't work, but leaving up anyways.

SELECT @row := @row + 1 AS row, ... FROM yourtable, (SELECT @row := -1) as foo ... HAVING row % 2 = 0

yes possible using temp variable

Example :

set @a := 0;
select * from car_m_city  WHERE mod((@a:=@a+1), 2) = 1

Explanation :

here in sql we declare @a( set @a := 0;) temp variable.(@a:=@a+1) now @a increment by 1.jsut like simple way to check odd or even

mod((@a:=@a+1), 2) = 1 for odd data

mod((@a:=@a+1), 2) = 0 for even data

This works for me.

    SET @row_number = 0;

    select* from (
        SELECT 
        (@row_number:=@row_number + 1) AS num, col1,col2
    FROM
        TABLE1
        ) as t WHERE num%2=0

You can use mod 1 for odd or mod 0 for even rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!