2013-02-10 83 views
2

我在mysql中有一個表,我從這個表中獲取結果。但不是取出這個表中的所有行,我只想獲取其他每一行。所以先得到第一行然後跳過第二行,得到第3行,並跳過第4行等。如何跳過mysql中的每一行?

有沒有這樣做的方法,如果有的話,可以請教我怎麼做。

我已經試過這樣:

功能:

function blocked_users_list() { 
      global $connection; 
      global $_SESSION; 
      global $profile_id; 
      $query = "SELECT 
    baseview.* 
    @odd:[email protected] 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 
+1

爲什麼你想要每隔一行,除了每隔一秒還有一行可以被識別嗎? – 2013-02-10 19:14:33

+0

[你如何從mysql中選擇每一個第n行]可能的重複(http://stackoverflow.com/questions/858746/how-do-you-select-every-n-th-row-from-mysql) – dotancohen 2013-12-05 16:37:13

回答

2

做查詢:

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

請檢查我的更新的問題,看看我是否已經正確地完成了這一點,謝謝 – 2013-02-10 19:16:05

+0

@NickJames我的平常回答是「它工作」嗎?如果是,那麼你是正確的,如果不是發佈錯誤。 – 2013-02-10 19:24:01

+0

錯誤列在問題中,不,它不工作。謝謝 – 2013-02-10 19:25:37

-1

使用一個變量來記錄的索引,然後用模2($ind % 2)檢查 - 這將返回0或1

<?php 
    $users_list = users_list(); 
    $ind = 0; 
    while ($user = mysql_fetch_array($users_list)) { 
     if(($ind++)%2) echo "something"; 
    } 
?> 
0

假設你有一個像

SELECT 
    col1 AS colA, 
    col2 AS colB 
FROM 
    sometable 
WHERE 
    something=17 
查詢

提取所有行作爲基準。然後,您可以通過使用

SELECT 
    baseview.* 
    @odd:[email protected] 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 
1

你可以在MySQL中使用模量(一個查詢)

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

獲取所有的奇數編號篩選中每隔一行。