从多个表中选择数据

时间:2012-10-28 12:23:47

标签: mysql sql select

如何通过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  |

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

1 个答案:

答案 0 :(得分:2)

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

join

的版本
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 Fiddle Demo

的版本子选择而不是连接

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 Fiddle Demo