這基本上是PIVOT
,但MySQL沒有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 with Demo
如果你有數目不詳的課程,那麼你可以使用一個事先準備好的聲明,與此類似:
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 with demo
,你能否告訴我們,在他們的一些測試值的三個表的設計? – Blueboye