doukou4066 2012-12-18 22:52
浏览 14
已采纳

如何从n开始选择mySQL中的每一行

I have created a question Here That I think is a little bloated. To skim down this question here is my requirements:

I need to create 3 mySQL queries that grab all information in that row so that I can format the information into one of HTML tables.

Here is the query that I have which selects everything:

$qry_questions = mysql_query("SELECT * FROM mbr_qa_questions ORDER BY q_votes DESC);
while($row = mysql_fetch_array($qry_questions){
    //Grab all information
}

Now, I need to make three queries that act like the one above, but I need it to do something like this:

pull everything from every third row in a table starting at row #1
pull everything from every third row in a table starting at row #2
pull everything from every third row in a table starting at row #3

Then I would put each of those queries into one of the 3 columns.

I can not do this by unique ID. Yes, it is an auto incrementing ID, but it will be probable that I might have to move whole rows into another table.

EDIT: I've added my attempt to count each row and place the queried result into the right "bin"

//GIVE EACH ENTRY A COLUMN NUMBER
$count++;
if($count >= 4){
    $count = 1; 
}?> 

<div class="col" id="col-1">
    <?PHP
    while($count == 1){
        include("pieces/answers/newAnswerLayout.php"); 
    }
    ?>
</div>
<div class="col" id="col-2">
    <?PHP
    while($count == 2){
        include("pieces/answers/newAnswerLayout.php"); 
    }
    ?>
</div>
<div class="col" id="col-3">
    <?PHP
    while($count == 3){
        include("pieces/answers/newAnswerLayout.php"); 
    }
    ?>
</div>
  • 写回答

3条回答 默认 最新

  • doumi1311 2012-12-18 23:08
    关注

    Here's one approach, to get the resultset returned by MySQL. (But it might be easier to just return all the rows, and get every third row within the app). But it can be done in MySQL pretty easily. Note that your original query is wrapped in parens (as an inline view) aliased as r.

    SELECT r.*
      FROM ( 
             SELECT *
               FROM mbr_qa_questions
              ORDER BY q_votes DESC
           ) r
     CROSS
      JOIN ( SELECT @i := 0 ) s
    HAVING ( @i := @i + 1) MOD 3 = 1
    

    That will return every third row, starting with the first row. To get every third row starting with the 2nd and 3rd row, replace the literal = 1 in the HAVING clause with = 2 or = 3 (respectively).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度