0

样品表:

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         
4

1 回答 1

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
于 2013-02-10T23:56:10.587 回答