在一行中选择表3行

时间:2017-11-30 01:13:16

标签: php mysql row

我有结果表需要在一行中获取所有Sub_ID内联行Sub_ID(17,18,19)

在像这样的查询中:

SELECT * 
FROM `results`
WHERE `ExamID` = 1

结果表

+----+-------+--------+--------+-------+-------+-------+
| ID | StuID | Sub_ID | ExamID | Exam1 | Exam2 | Exam3 |
+----+-------+--------+--------+-------+-------+-------+
|  1 |    70 |     17 |      1 |     0 |     0 |     0 |
|  2 |    70 |     18 |      1 |     0 |     0 |     0 |
|  3 |    70 |     19 |      1 |     0 |     0 |     0 |
|  4 |    70 |     24 |      4 |     0 |     0 |     0 |
|  5 |    70 |     25 |      4 |     0 |     0 |     0 |
+----+-------+--------+--------+-------+-------+-------+

在页面中显示表格

需要将所有Sub_ID内联到ExamID = 1

如何编写我的SQL语句,以获得类似这样的结果?:

+----+-------+--------+--------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
| ID | StuID | Sub_ID | ExamID | Exam1 | Exam2 | Exam3 | StuID | Exam1 | Exam2 | Exam3 | StuID | Exam1 | Exam2 | Exam3 |
+----+-------+--------+--------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
|  1 |    70 |     17 |      1 |     0 |     0 |     0 |    18 |     0 |     0 |     0 |    19 |     0 |     0 |     0 |
+----+-------+--------+--------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+

需要MySQL查询来获取该表

1 个答案:

答案 0 :(得分:1)

您好,您可以使用以下查询来获得与您请求的结果类似的内容。

解决方案1 ​​

  

注意:您不会以列方式获取值,而是将逗号分隔在一列中。

SELECT GROUP_CONCAT(id,',',StuID,',', Sub_ID,',',ExamID,',',Exam1,',',Exam2,',',Exam3) 
FROM `results` 
GROUP BY ExamID

示例输出:

GROUP_CONCAT(id,',',StuID,',', Sub_ID,',',ExamID,',',Exam1,',',Exam2,',',Exam3)
1,70,17,1,0,0,0,2,70,18,1,0,0,0,3,70,19,1,0,0,0
4,70,20,4,0,0,0,5,70,21,4,0,0,0

如果您想让每一行在第7列之后爆炸(考虑您的列),请在 foreach 循环

中使用以下代码段
array_chunk(explode(';', $input), 7);

注意:删除select。的GROUP_CONCAT()中不需要的列。

解决方案2

如果您不希望以上述方式获得结果,那么唯一的解决方案就是从数据库表中获取所有结果并循环到它们中并实现您想要的结果。

已更新

首先,您需要查询所有记录,然后执行所需的操作。让我给小片段。但同样取决于你想要达到的目标。

$resultsQuery = mysqli_query($con, "SELECT * FROM results");
$finalResults = array();
if(mysqli_num_rows($resultsQuery) > 0){
    while($row = mysqli_fetch_assoc($resultsQuery)){
        /* 
            Here you can write your script

                    OR

            Store the $row in an array and do as per your needs
         */
    }
}