我有两个数据表;
A表:
  科目     ID
  语文       1 
  数学       2
  外语       3
  c#       4B表:
专业          课程1     课程2
软件设计       1         4
电子商务       2         3
怎么查询才能使它们的结果得到:
专业        课程1       课程2
软件设计     语文         C#
电子商务     数学         外语

解决方案 »

  1.   

    create table Subject 
    (
    id int identity(1,1) primary key,
    name nvarchar(50)
    )
    insert into Subject([name]) values('语文')
    insert into Subject([name]) values('数学')
    insert into Subject([name]) values('外语')
    insert into Subject([name]) values('C#')
    create table Speciality
    (
    name nvarchar(100) primary key,
    subid1 int not null,
    subid2 int not null
    )
    insert into Speciality values('软件设计',1,2)
    ------------------------------------------------
    SELECT     Speciality_1.name, Subject_1.name AS 课程1,
                              (SELECT     dbo.Subject.name AS Expr1
                                FROM          dbo.Speciality INNER JOIN
                                                       dbo.Subject ON dbo.Speciality.subid1 = dbo.Subject.id) AS 课程2
    FROM         dbo.Speciality AS Speciality_1 INNER JOIN
                          dbo.Subject AS Subject_1 ON Speciality_1.subid2 = Subject_1.id
      

  2.   


    create table #ta
    (科目 varchar(10) not null,
     ID   int not null)
    insert into #ta
    select '语文',1
    union all
    select '数学',2
    union all
    select '外语',3
    union all
    select 'C#',4create table #tb
    (专业 varchar(10) not null,
     课程1 int not null,
     课程2 int not null)insert into #tb
    select '软件设计',1,4
    union all
    select '电子商务',2,3 
    select a.专业,a.课程1,b.课程2
    from (select #ta.科目 as 课程1,#tb.专业
          from #ta,#tb
          where #ta.ID=#tb.课程1) a,
         (select #ta.科目 as 课程2,#tb.专业
          from #ta,#tb
          where #ta.ID=#tb.课程2) b
    where a.专业=b.专业
    结果:
     专业    课程1    课程2
    电子商务 数学 外语
    软件设计 语文 C#
      

  3.   

    select a.name,b.name,c.name 
    from Speciality a 
    left join subject b on a.subid1 = b.id
    left join subject c on a.subid2 = c.id
      

  4.   

    select b.专业,(select a.科目 from A表 a where b.课程1=a.ID) as  课程1,(select a.科目 from A表 a where b.课程2=a.ID) as  课程2 from B表 b