根据主题类型将mysql行提取到表中

时间:2013-03-19 19:15:43

标签: php mysql

以下是我的表格样本(为清晰起见重新格式化)

  Subject   Percentage  Grade
  English     40%       D
  Chemistry   80%       A
  Physics     50%       C

所以,基本上我想获取这些数据并用这种方式表示:

  English   Chemistry    Physics
  40%           80%        50%
  D              A          C

我该怎么做? 谢谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

    select english , chemistry , physics from (


    select (select percentage from Table1 where subject = 'English' ) as english,
           (select percentage from Table1 where subject = 'Chemistry') as chemistry,
           (select percentage from Table1 where subject = 'Physics') as physics

    from Table1 group by english
    union all

    select (select Grade from Table1 where subject = 'English' ) as english,
           (select Grade from Table1 where subject = 'Chemistry') as chemistry,
           (select Grade from Table1 where subject = 'Physics') as physics

    from Table1 group by english
     ) t

<强>输出:

 ENGLISH    CHEMISTRY   PHYSICS
  40%          80%        50%
   D            A          C

DEMO HERE

答案 1 :(得分:0)

将数据提取到数组中,然后循环遍历数组以填充表行

$subject = array();
$row = mysql_fetch_row($result);
{
    $subjecta = $row[0]; 
    $marks =  $row[1];
    $grade =  $row[2];
    array_push($subject,$subjecta)
    $subject[$marks] = $grade ;
    $subject[$grade] = $marks ;

}
echo "<tr>";
foreach ($subject as $sts) 
{ 
echo "<th bgcolor='#BEBEBE'>$sts</th>"; 
}
echo "</tr>";