我如何跳过mysql中的每一行?

时间:2013-02-10 19:02:51

标签: php mysql

我在mysql中有一个表,我从这个表中获取结果。但不是获取此表中的所有行,而是只想获取每隔一行。所以先获取第一行,然后跳过第二行,获取第3行并跳过第4行等。

有没有办法做到这一点,如果是这样,有人可以告诉我如何。

我试过这个:

功能:

function blocked_users_list() {
            global $connection;
            global $_SESSION;
            global $profile_id;
            $query = "SELECT
  baseview.* 
  @odd:=1-@odd AS even
FROM 
  (
   SELECT *
    FROM ptb_block_user
    WHERE
      WHERE ptb_block_user.blocked = '1'
      AND ptb_block_user.blocked_id = ".$_SESSION['user_id']."
  ) AS baseview,
  (
    SELECT @odd:=0
  ) AS filter
WHERE
  even=1                
                        ";
            $blocked_users_list = mysql_query($query, $connection);
            confirm_query($query, $connection);
            return $blocked_users_list;
        }

PHP:

<?php
        $blocked_users_list = blocked_users_list();
        while ($block = mysql_fetch_array($blocked_users_list)) { 



?>

但它会出现此错误:

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/ptb1/blocked_users.php on line 44

2 个答案:

答案 0 :(得分:2)

在查询中执行:

SELECT * 
FROM ( 
    SELECT 
        @row := @row +1 AS rownum, [column name] 
    FROM ( 
        SELECT @row :=0) r, [table name] 
    ) ranked 
WHERE rownum % [n] = 1

答案 1 :(得分:0)

假设您有像

这样的查询
SELECT 
  col1 AS colA,
  col2 AS colB
FROM
  sometable
WHERE
  something=17

所有行作为基线获取。然后,您可以使用

过滤每隔一行
SELECT
  baseview.* 
  @odd:=1-@odd AS even
FROM 
  (
    SELECT 
      col1 AS colA,
      col2 AS colB
    FROM
      sometable
    WHERE
      something=17
  ) AS baseview,
  (
    SELECT @odd:=0
  ) AS filter
WHERE
  even=1