select every other row in MySQL without depending

2019-01-26 19:21发布

Considering following table that doesn't have any primary key, can I select every other row?

col1      col2
 2         a
 1         b
 3         c
 12        g

first select must find: 2, 3

second select must find: 1, 12

is that possible?

7条回答
狗以群分
2楼-- · 2019-01-26 20:04

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

查看更多
贪生不怕死
3楼-- · 2019-01-26 20:07

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.

查看更多
贼婆χ
4楼-- · 2019-01-26 20:12

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

查看更多
家丑人穷心不美
5楼-- · 2019-01-26 20:13

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.

查看更多
We Are One
6楼-- · 2019-01-26 20:15

doesn't work, but leaving up anyways.

SELECT @row := @row + 1 AS row, ... FROM yourtable, (SELECT @row := -1) as foo ... HAVING row % 2 = 0
查看更多
We Are One
7楼-- · 2019-01-26 20:16

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

查看更多
登录 后发表回答