我想使用PHP处理来自mysql的数据,以便在HTML中显示。 我有三个数据库表:学生,课程,student_x_course
学生:
| idStudent | firstname | surname |
-----------------------------------
| 1 | John | Regular |
| 2 | John | Smith |
| 3 | Claire | White |
当然:
| idCourse | coursename |
--------------------------
| 1 | Art |
| 2 | Music |
| 3 | Math |
| 3 | Biology |
student_x_course:
| idsc | idStudent | idCourse |
-------------------------------
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 2 | 4 |
| 7 | 3 | 1 |
| 8 | 3 | 2 |
| 9 | 3 | 3 |
| 10 | 3 | 4 |
我想创建一个看起来像这样的html表:
| Art | Music | Math | Biology |
------------------------------------------------
John Regular | x | x | x | - |
John Smith | x | x | - | x |
Claire White | x | x | x | x |
我的SQL查询是: SELECT s.firstname,s.surname,c.coursename FROM student AS s INNER JOIN student_x_course AS sxc ON(s.idStudent = sxc.idStudent)INNER JOIN课程ON(c.idCourse = sxc.idCourse);
让我得到以下信息:
| John | Regular | Art |
| John | Regular | Music |
| John | Regular | Math |
| John | Smith | Art |
| John | Regular | Music |
| John | Smith | Biology |
| Claire | White | Art |
| Claire | White | Music |
| Claire | White | Math |
| Claire | White | Biology |
我的问题是:如何从多行到多行? 是否有更好的SQL查询或我必须在PHP代码中处理这个? 有什么建议吗?
答案 0 :(得分:1)
您正试图转动结果。在mysql
中,您可以使用conditional aggregation
执行此操作:
SELECT s.idStudent, s.firstname, s.surname,
max(case when c.coursename = 'Art' then 'x' end) Art,
max(case when c.coursename = 'Music' then 'x' end) Music,
max(case when c.coursename = 'Math' then 'x' end) Math,
max(case when c.coursename = 'Biologoy' then 'x' end) Biologoy
FROM student AS s
INNER JOIN student_x_course AS sxc ON (s.idStudent = sxc.idStudent)
INNER JOIN course ON (c.idCourse = sxc.idCourse)
GROUP BY s.idStudent