我有一个类似这样的表:
Lecture_ID | Subject | Section | time_Date
0001 | Maths | A | ....
0002 | Maths | B | ....
0003 | Maths | C | ....
0004 | Maths | B | ....
我希望数据应按部分分组,以便当我 echo
时输出数据,应该是这样的:
Section A
time_Date
time_Date
Section B
time_Date
time_Date
...
我怎样才能实现查询来做这样的事情..我所拥有的就像
$query = 'SELECT * FROM Lecutre_info WHERE Subject="'.$_GET['subject'].'" ORDER BY Section ASC';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
print '<h1>'.$row['Section']
print '<br>'.$row['time_Date'];
}
你可以想象我有Section
每一条记录。我如何将条目分组在一起。另外,我不知道事先会有多少部分,并且部分可以从任何字母开始,不一定是“A”。所以例如可能有一门科学课,其中有 1 个部分名为 X。谢谢...
最佳答案
下面的sql将输出你想要的内容:
参见 fiddle :http://sqlfiddle.com/#!2/ea7f7b/21/0
select case when length(section) = 1 then
concat('Section ',section)
else substring_index(section, '/', -1)
end as result
from (select distinct section
from tbl
union all
select concat(section, '/', dt)
from tbl
order by 1) x
关于php - 使用 SQL 和 PHP 对数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24974585/