假设我有一个类似于以下内容的数据库:
表student_info:
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
...
如果是这样,语法是什么?我不知道这是一个连接操作还是其他什么?
感谢。
答案 0 :(得分: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
否则,当你有不知道的分数时,首选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 ║
╚══════════════╩══════════════╩══════════════╝
答案 1 :(得分: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 |