这基本上是 a PIVOT
,但 MySQL 没有 a ,PIVOT
因此您需要使用聚合和CASE
语句来复制它。如果您知道要获取值的课程名称,则可以对其进行硬编码:
select u.userName,
max(case when c.coursename = 'Course 1' then s.completed_date end) Course1,
max(case when c.coursename = 'Course 2' then s.completed_date end) Course2,
max(case when c.coursename = 'Course 3' then s.completed_date end) Course3
from users u
left join test_sessions s
on u.user_id = s.user_id
left join courses c
on s.course_id = c.course_id
group by u.username
请参阅带有演示的 SQL Fiddle
如果您的课程数量未知,则可以使用准备好的语句,类似于:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when c.coursename = ''',
coursename,
''' then s.completed_date end) AS ',
coursename
)
) INTO @sql
FROM courses;
SET @sql = CONCAT('SELECT u.userName, ', @sql, '
from users u
left join test_sessions s
on u.user_id = s.user_id
left join courses c
on s.course_id = c.course_id
group by u.username');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
请参阅带有演示的 SQL Fiddle