Mysql根据结果创建虚拟列

时间:2014-04-03 05:32:20

标签: mysql

我有5张桌子: users user_profiles courses user_subjects subjects

用于使用此查询为每个用户提取相关主题:

SELECT
    --snip--
    u.id,
    u.username,
    u.level,
    c.name course_expertise,
    GROUP_CONCAT(s.name ) subjects
FROM
    user_profiles up
INNER JOIN users u ON up.user_id = u.id
INNER JOIN courses c ON up.course_expertise_id = c.id
INNER JOIN user_subjects us ON u.id = us.user_id
INNER JOIN subjects s ON us.subject_id = s.id
GROUP BY u.id

导致:

+----+-----------+-----------+-----------------------------------+-------------------+
| id | username  | level     | course_expertise                  | subjects          |
+----+-----------+-----------+-----------------------------------+-------------------+
|  2 | lecturer  | lecturer  | Information Technology Management | sub1, sub2, sub3  |
|  3 | professor | professor | Information Technology Management | sub4, sub 5, sub6 |
+----+-----------+-----------+-----------------------------------+-------------------+

有没有办法可以实现这样的目标:

+----+-----------+-----------+-----------------------------------+----------+----------+----------+
| id | username  | level     | course_expertise                  | subject1 | subject2 | subject3 |
+----+-----------+-----------+-----------------------------------+----------+----------+----------+
|  2 | lecturer  | lecturer  | Information Technology Management |   sub1   |   sub2   | sub3     |
|  3 | professor | professor | Information Technology Management |   sub4   |   sub5   | sub6     |
+----+-----------+-----------+-----------------------------------+--------------------------------+

被修改 subjects列,将始终包含3个主题

2 个答案:

答案 0 :(得分:2)

如果只有3个科目,那么它将正常工作。

select ID,
username,
level,
name course_expertise,
SUBSTRING_INDEX(subjects,',','1') subject1,
SUBSTRING_INDEX(SUBSTRING_INDEX(subjects,',','2'),',','-1') subject2,
SUBSTRING_INDEX(SUBSTRING_INDEX(subjects,',','3'),',','-1') subject3
 from
(

SELECT
    u.id,
    u.username,
    u.level,
    c.name course_expertise,
    GROUP_CONCAT(s.name ) subjects
FROM
    user_profiles lp
INNER JOIN users u ON lp.user_id = u.id
INNER JOIN courses c ON lp.course_expertise_id = c.id
INNER JOIN user_subjects us ON u.id = us.user_id
INNER JOIN subjects s ON us.subject_id = s.id
GROUP BY u.id

) A

答案 1 :(得分:1)

更改

GROUP_CONCAT(s.name ) subjects

max( case when s.name in( 'sub1', 'sub4' ) then s.name else null end ) as 'Subject 1'  
, max( case when s.name in( 'sub2', 'sub5' ) then s.name else null end ) as 'Subject 2'  
, max( case when s.name in( 'sub3', 'sub6' ) then s.name else null end ) as 'Subject 3'