1

假设我有一个类似于以下的数据库:

表学生信息:

id    name
111   jon
112   dan
113   david
...

和表分数:

item_id    student_id    score
01         111           37
02         111           45
01         112           55
02         112           44
01         113           66
02         113           45
...

是否可以执行 mysql 查询来生成下表?:

Student_Name  ITEM_1_SCORE  ITEM_2_SCORE
jon           37            45
dan           55            44
david         66            45
...

如果是这样,语法是什么?不知道这是join操作还是别的什么?

谢谢。

4

2 回答 2

7

如果你只有两个值item_id,那么硬编码值是可以的。例子

SELECT  a.Name AS Student_Name,
        MAX(CASE WHEN item_id = '01' THEN b.score END) Item_1_Score,
        MAX(CASE WHEN item_id = '02' THEN b.score END) Item_2_Score
FROM    student_info a
        LEFT JOIN scores b
            ON a.id = b.student_ID
GROUP   BY a.Name

否则,当您不知道分数时,更喜欢 a Dynamic SQL

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('MAX(CASE WHEN item_id = ''',
               item_id,
               ''' THEN Score END) AS ',
               CONCAT('`Item_', item_id, '_Score`')
               )) INTO @sql
FROM scores;

SET @sql = CONCAT('SELECT   a.Name AS Student_Name, ', @sql, ' 
                    FROM    student_info a
                            LEFT JOIN scores b
                                ON a.id = b.student_ID
                    GROUP   BY a.Name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

两个查询都将输出相同的

╔══════════════╦══════════════╦══════════════╗
║ STUDENT_NAME ║ ITEM_1_SCORE ║ ITEM_2_SCORE ║
╠══════════════╬══════════════╬══════════════╣
║ dan          ║           55 ║           44 ║
║ david        ║           66 ║           45 ║
║ jon          ║           37 ║           45 ║
╚══════════════╩══════════════╩══════════════╝
于 2013-05-18T00:15:59.883 回答
4

像这样:

SELECT
  i.name AS Student_Name,
  MAX(CASE WHEN s.item_id = 1 THEN score END) AS ITEM_1_SCORE, 
  MAX(CASE WHEN s.item_id = 2 THEN score END) AS ITEM_2_SCORE
FROM student_info AS i
INNER JOIN scores AS s ON s.student_id = i.id
GROUP BY i.name;

在这里查看它的实际效果:

这会给你:

| STUDENT_NAME | ITEM_1_SCORE | ITEM_2_SCORE |
----------------------------------------------
|          dan |           55 |           44 |
|        david |           66 |           45 |
|          jon |           37 |           45 |
于 2013-05-18T00:14:57.603 回答