如何在子查询中使用两个表达式

时间:2014-07-30 08:52:40

标签: sql sql-server

我有两张桌子

MARKS

  • Roll
  • SubA(包含主题代码)
  • SubB(包含主题代码)
  • SubC(包含主题代码)
  • ....
  • ....

SUBJECT

  • Sub_Code
  • Sub_Name
  • Sub_Opt(包含理论/实践等选项)

当我写这个查询时

Select 
    Roll, 
    (Select Sub_Name From Subject Wwhere dbo.marks.subA = dbo.subject.sub_code), 
    (Select Sub_Name From Subject where dbo.marks.SubB = dbo.subject.sub_code) 
from marks, subject

它成功运行,但是当我尝试在子查询中添加主题选项时 -

    select 
    Roll, 
    ( SELECT    Sub_name ,
                Sub_Opt
      FROM      subject
      WHERE     dbo.marks.SubA = dbo.subject.Sub_Code
    ) 
    ( SELECT    Sub_name ,
                Sub_Opt
      FROM      subject
      WHERE     dbo.marks.SubB = dbo.subject.Sbu_Code
    ) 
from Marks, subject

导致错误:

  

当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。

我想要这种格式的结果

ROLL, SUB_NAME_A, SUB_OPT_A, SUB_NAME_B, SUB_OPT_B, SUB_NAME_C, SUB_OP_C,......

2 个答案:

答案 0 :(得分:0)

如果join表中没有数据保证

,那么您可以LEFT JOIN在表格中SUBJECT代替内部
   SELECT  m.Roll ,
            a.Sub_name ,
            a.Sub_Opt ,
            b.Sub_name ,
            b.Sub_Opt
    FROM    marks m
            INNER JOIN SUBJECT a ON m.SubA = a.Sub_Code
            INNER JOIN SUBJECT b ON m.SubB = b.Sub_Code
            etc

答案 1 :(得分:0)

选择     滚,     (SELECT Sub_name                  来自主题       WHERE dbo.marks.SubA = dbo.subject.Sub_Code     )SUB_NAME_A,     (SELECT Sub_Opt       来自主题       WHERE dbo.marks.SubA = dbo.subject.Sub_Code     )SUB_OPT_A,

( SELECT    Sub_name 
  FROM      subject
  WHERE     dbo.marks.SubB = dbo.subject.Sub_Code
)  SUB_NAME_B ,
( SELECT    Sub_Opt 
  FROM      subject
  WHERE     dbo.marks.SubB = dbo.subject.Sub_Code
) SUB_OPT_B ,

来自Marks

this also should work