drtppp75155 2016-04-06 02:14
浏览 24
已采纳

获取一些表/数组的mysql查询

i have some table scores like this...

id A  B  score
1  10 4  100
2  10 2  320
3  10 1  100
4  20 4  20
5  20 3  100
6  20 2  120
7  20 1  110 
8  30 4  30
9  30 3  200

and i want some query or php method to make output like

column A =>    10    20     30
         4 =   100   20     30
         3 =   null   100    200
         2 =   320   120    null
         1 =   100   110    null
         ^
        ||
       (coumn b)

or

         4 ,100,20,30
         3 ,null,100,200
         2 ,320,120,null
         1 ,100,110,null

so i want get column score but based on coumn B, if column A don't have a row score of one column B, will give null.

i have tried full join, cross join, etc but i failed to get that's like it.

  SELECT * FROM TABLE CROSS JOIN
       (SELECT * FROM TABLE CROSS GROUP BY B)
  ORDER BY B DESC

thanks

  • 写回答

1条回答 默认 最新

  • dongxian1921 2016-04-06 02:38
    关注

    Here is another way you can do it doing a nested loop (using mysqli_*):

    echo '<table>';
    
    $stmt = $connection->prepare("SELECT B FROM TABLE ORDER BY B DESC");
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($b);
    while($stmt->fetch()){
    
        echo '<tr>
                  <td>'.$b.'</td>';
    
        $stmt2 = $connection->prepare("SELECT A FROM TABLE GROUP BY A ORDER BY A");
        $stmt2->execute();
        $stmt2->store_result();
        $stmt2->bind_result($a);
        while($stmt2->fetch)){
    
            $stmt3 = $connection->prepare("SELECT score FROM TABLE WHERE A = ? AND B = ?");
            $stmt3->bind_param("ii", $a, $b);
            $stmt3->execute();
            $stmt3->store_result();
            if($stmt3->num_rows > 0){
                $stmt3->bind_result($score);
                $stmt3->fetch();
                echo '<td>'.$score.'</td>';
            } else {
                echo '<td>NULL</td>';
            }
            $stmt3->close();
    
        } /* END OF WHILE LOOP OF SECOND STATEMENT */
        $stmt2->close();
    
        echo '</tr>'; /* END OF ROW */
    
    } /* END OF WHILE LOOP */
    $stmt->close();
    
    echo '</table>';
    

    But I'm pretty sure someone would answer your question in a single query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。