0

如何通过mysql在一行中加入多行?

例子 :

学生桌

Sno.|  Name |  Subjects
1.  | ABC   |  1
2.  | ABC   |  3
3.  | ABC   |  4
4.  | FMC   |  2
5.  | ABC   |  4
6.  | JBC   |  4

论文表:

Sno. | Paper Name | Type 
 1.      French     Optional
 2.      English    Mandatory
 3.      Japenese   Optional
 4.      Maths      Optional

现在我想要这种格式

Sno.| Name|   Sub1  |  Sub2    | Sub3  |  Sub4 |
1.  | ABC |  French |  Japenese| Maths | Null  |
2.  | FMC |  Null   | Null     | Null  | Null  |
3.  | JBC |  Maths  | Null     | Null  | Null  |

我要选择的是论文表中的论文名称和学生姓名,另一个表中的四个科目。我只想看那些可选的论文。我不知道该怎么办?

4

1 回答 1

2

我认为您正在寻找的概念是旋转的。

连接的版本

select 
  name,
  max(if(s.subject = 1 and p.type = 'Optional', p.paper_name, null)) as subject1,
  max(if(s.subject = 2 and p.type = 'Optional', p.paper_name, null)) as subject2,
  max(if(s.subject = 3 and p.type = 'Optional', p.paper_name, null)) as subject3,
  max(if(s.subject = 4 and p.type = 'Optional', p.paper_name, null)) as subject4
from 
  students s
inner join
  papers p on p.sno = s.subject
group by s.name

SQL 小提琴演示

带有子选择而不是连接的版本

select 
  name,
  max(
    case 
      when subject = 1 
        then (select paper_name from papers p where p.sno = subject and type = 'Optional') 
      else 
        null 
    end) as subject1, 
  max(
    case 
      when subject = 2 
        then (select paper_name from papers p where p.sno = subject and type = 'Optional') 
      else 
        null 
    end) as subject2,
  max(
    case 
      when subject = 3 
        then (select paper_name from papers p where p.sno = subject and type = 'Optional') 
      else 
        null 
    end) as subject3,
  max(
    case 
      when subject = 4
        then (select paper_name from papers p where p.sno = subject and type = 'Optional') 
      else 
        null 
    end) as subject4
from 
  students
group by 
  name

SQL 小提琴演示

于 2012-10-28T14:10:13.637 回答