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

后端 未结 5 976
独厮守ぢ
独厮守ぢ 2020-12-18 07:36

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               


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 08:30

    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

提交回复
热议问题