样本表:
name subject grade status
-----------------------------------------
john peter engl NULL X
john peter math 85 A
john peter philo NULL X
mark lewis engl 90 A
mark lewis math NULL X
示例查询:
<?php
$query="SELECT name, grade, status, group_concat(subject SEPARATOR '-') as subj
FROM grades GROUP BY name ORDER BY name";
$result = $mysqli->query($query);
<?php } ?>
<table>
<tr>
<td>name</td>
<td>Math</td>
<td>English</td>
<td>Philosopy</td>
</tr>
<?php while($row = $result->fetch_array()){ ?>
<tr>
<td><?php echo $row['name'];?></td>
<td><?php if (strpos($row['subj'],'math')!== false) {echo 'I';}?></td>
<td><?php if (strpos($row['subj'],'engl')!== false) {echo 'I';}?></td>
<td><?php if (strpos($row['subj'],'philo')!== false) {echo 'I';}?></td>
</tr>
<?php } ?>
</table>
示例输出:
name Math English Philosopy
john peter I I I
mark lewis I I
现在出现了我想要实现的目标:
如果它的值是X,我想显示状态,
像这样:还是有更好的方法来做到这一点?
谢谢你们..
name Math English Philosopy
john peter I X I
mark lewis X I
答案 0 :(得分:0)
试试这个,
SELECT name,
MAX(CASE WHEN subject = 'Math' THEN IF(status = 'X', 'X', 'I') END) MATH,
MAX(CASE WHEN subject = 'Engl' THEN IF(status = 'X', 'X', 'I') END) ENGLISH,
MAX(CASE WHEN subject = 'Philo' THEN IF(status = 'X', 'X', 'I') END) Philiosophy
FROM tableName
GROUP BY name