过滤表列并查看另一列中的数据

-9 php mysql sql pivot

表'acad_concerns'

id  student_name    start_date  end_date    concern         comments

 1  Anne Curtis     2013-02-27  2013-02-28  Academics       this acad.. 
2   benedict grey   2013-02-27  2013-02-28  Academics       also acad..
3   Anne Curtis     2013-02-27  2013-02-28  Accomodation    this is aco
4   benedict grey   2013-02-27  2013-02-28  Accomodation    also accomo
Run Code Online (Sandbox Code Playgroud)

我想这样看:

    student_name    Accademics   Accomodation   


    Anne Curtis     this acad..  this is accom..
    benedict grey   also acad..  also accom..
Run Code Online (Sandbox Code Playgroud)

Mah*_*mal 6

我无法解释这一点

让我为你解释一下.

您正在寻找旋转comments的价值观concern为每一位学生.不幸的是,MySQL没有数据透视表运算符.

但是,您可以使用CASE表达式执行此操作.像这样:

SELECT 
  student_name,
  MAX(CASE WHEN concern = 'Academics'   THEN comments END) AS 'Accademics',
  MAX(CASE WHEN concern = 'Accomodation' THEN comments END) AS 'Accomodation'
FROM acad_concern    
GROUP BY student_name;
Run Code Online (Sandbox Code Playgroud)

SQL小提琴演示

这会给你:

|  STUDENT_NAME |  ACCADEMICS | ACCOMODATION |
----------------------------------------------
|   Anne Curtis | this acad.. |  this is aco |
| benedict grey | also acad.. |  also accomo |
Run Code Online (Sandbox Code Playgroud)

对于多个concerns并且您不需要手动编写它们,您必须使用动态SQL动态执行此操作,如下所示:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(concern = ''',
      concern, ''', comments, NULL)) AS ', '''', concern , '''')
  ) INTO @sql
FROM acad_concern;

SET @sql = CONCAT('SELECT student_name, ', @sql , '
    FROM acad_concern    
    GROUP BY student_name;');

prepare stmt 
FROM @sql;

execute stmt;
Run Code Online (Sandbox Code Playgroud)

更新了SQL小提琴演示