如何在同一个表中使用多个UNION

时间:2017-07-03 07:51:10

标签: php mysql while-loop union

从HTML TABLE表单中的结果表中获取数据时遇到问题。我有一个表结果,其中包含有关学生结果的信息,其中标记列具有多个值,如 SA1,SA2,SA3,Mid_term,Final
因此,在此查询中,我从first_name获取marksresults table 问题是我获得SA1 column下的所有标记,但我希望SA1 marks位于SA1 Column SA2 marks SA2 Column SA3 marks下的SA3 Column下。{ 我几乎尝试了一切,但我无法弄清楚我在做什么错误。

这是我的代码

echo '<table class = "w3-table">
<tr> 
<td> Name </td>
<td> SA1 </td>
<td> SA2 </td>
<td> SA3 </td>
<td> Mid-term </td>
<td> Final </td>
</tr>
<tr>
';
$q = "(SELECT first_name, marks  FROM results WHERE class = '11th Arts' AND 
subject = 'Arts' AND exam_type = 'SA1' )
     UNION ALL (SELECT  NULL, marks as m1  
FROM results WHERE class = '11th Arts' AND subject = 'Arts' 
AND exam_type = 'SA2' ) 
     UNION ALL (SELECT  NULL, marks as m2  FROM results
 WHERE class = '11th Arts' AND subject = 'Arts' AND exam_type = 'SA3' )
     UNION ALL (SELECT  NULL, marks as m3  FROM results 
WHERE class = '11th Arts' AND subject = 'Arts' AND exam_type = 'Mid-term')
     UNION ALL (SELECT  NULL, marks as m4  FROM results 
WHERE class = '11th Arts' AND subject = 'Arts' AND exam_type = 'Final')";

$r = mysqli_query($dbc, $q)
or die(mysqli_error($dbc));
while($row = mysqli_fetch_assoc($r))
{
    $name = $row['first_name'];
    $marks = $row['marks'];
    $marks1 = $row['m1'];
    $marks2 = $row['m2'];
    $marks3 = $row['m3'];
    $marks4 = $row['m4'];
    echo '<tr>
         <td>' .$name .'</td>
         <td>'. $marks. '</td>
         <td>'. $marks1. '</td>
         <td>'. $marks2. '</td>
         <td>'. $marks3. '</td>
         <td>'. $marks4. '</td>
         </tr>';
}
echo '</table>';
?> 

1 个答案:

答案 0 :(得分:0)

您可以使用mySql WHEN CASE 来获得所需的输出。
试试这个

SELECT first_name,
case when exam_type = 'SA1' then marks end as m1,  
case when exam_type = 'SA2' then marks end as m2,
case when exam_type = 'SA3' then marks end as m3, 
case when exam_type = 'Mid-term' then marks end as m4,  
case when exam_type = 'Final' then marks end as m5 
FROM results
WHERE class = '11th Arts' AND 
subject = 'Arts'

你将以

的形式出局
$name = $row['first_name'];
$marks = $row['m1'];
$marks1 = $row['m2'];
$marks2 = $row['m3'];
$marks3 = $row['m4'];
$marks4 = $row['m5'];

我会帮助你。