【发布时间】:2016-06-23 22:26:08
【问题描述】:
我想使用 PHP 处理来自 mysql 的数据以在 HTML 中显示。 我有三个数据库表:student、course、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 |
学生_x_课程:
| 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 course 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 代码中处理这个? 有什么建议吗?
【问题讨论】: