2

我在 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
4

4 回答 4

2

在查询中执行:

SELECT * 
FROM ( 
    SELECT 
        @row := @row +1 AS rownum, [column name] 
    FROM ( 
        SELECT @row :=0) r, [table name] 
    ) ranked 
WHERE rownum % [n] = 1
于 2013-02-10T19:06:40.957 回答
1

您可以在 mysql 中使用模数(一个查询)

select * from `table` where `id` % 2 = 1

检索所有奇数 ID。

于 2013-02-10T19:30:54.490 回答
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
于 2013-02-10T19:08:42.377 回答
-1

使用变量记录索引,然后使用 mod 2 ( $ind % 2) 检查 - 这将返回 0 或 1。

<?php
    $users_list = users_list();
    $ind = 0;
    while ($user = mysql_fetch_array($users_list)) { 
        if(($ind++)%2) echo "something"; 
    } 
?>
于 2013-02-10T19:07:13.980 回答