0

我需要一点关于 sql 的帮助。

所以现在我有一个类似的查询:

   SELECT  q.id, 
           q.approved, 
           up.username, 
           h1.name AS h_name1, 
           h2.name AS h_name2,
           s.title,
           v.points
     FROM  votes v, questionaries q
     JOIN  (heroes h1, heroes h2, skills s)  
       ON  (q.hero1=h1.id AND q.hero2=h2.id AND  q.hero1 = s.hero_id)
     JOIN  user_profiles up 
       ON  q.user_id = up.user_id
    WHERE  s.id = v.skill
      AND  q.approved = 2

这样我得到下一个数据结构:

id appr username    h1    h2   skill points

32  2  username  hero1  hero2  skill1  42
32  2  username  hero1  hero2  skill2  35
32  2  username  hero1  hero2  skill3  43
32  2  username  hero1  hero2  skill4  23

...
and many rows

但所需的结构是:

id appr username   h1     h2     s1    s2      s3     s4     p1   p2   p3   p4

32  2    username  hero1 hero2 skill1 skill2 skill3 skill4   42   35   43   23

有没有办法像这样转换选择结果?

4

1 回答 1

2

Mysql 没有pivot,但是有group_concat。我认为以下内容可能会满足您的需求:

select id, approved, username, hero1, hero2,
       group_concat(title sep ',') as skills,
       group_concat(cast(points as varchar(255)) sep ',')
from (SELECT  q.id, 
              q.approved, 
              up.username, 
              h1.name AS h_name1, 
              h2.name AS h_name2,
              s.title,
              v.points
        FROM  votes v, questionaries q
        JOIN  (heroes h1, heroes h2, skills s)  
          ON  (q.hero1=h1.id AND q.hero2=h2.id AND  q.hero1 = s.hero_id)
        JOIN  user_profiles up 
          ON  q.user_id = up.user_id
       WHERE  s.id = v.skill
         AND  q.approved = 2
     ) t
group by id, approved, username, hero1, hero2

这会将技能和点放在一个逗号分隔的列表中,每个列表都在自己的列中。

于 2012-07-30T23:51:23.847 回答