2013-02-10 303 views
0

示例表:PHP的MySQL GROUP_CONCAT

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

爲什麼不測試/回聲'$行[ '狀態']',要麼打印'X'還是'我'? – Jon 2013-02-10 23:54:16

回答

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 
+0

*後續問題:在'match'中如何標記lewis'具有'x'的狀態?* – 2013-02-10 23:59:19