【问题标题】:Treat data from mysql for html将来自 mysql 的数据处理为 html
【发布时间】: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 代码中处理这个? 有什么建议吗?

【问题讨论】:

标签: php html mysql


【解决方案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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-05
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    相关资源
    最近更新 更多