合并列和子选择列表

时间:2018-03-02 14:57:29

标签: sql sql-server

我的查询看起来像:

SELECT col1, col2,
    (SELECT col3, col4 FROM Table2)
FROM Table1

通缉的结果是:

col1 | col2 | col3 | col4
-------------------------
ABC  | DEF  | GHI  | JKL
...  | ...  | ...  | ...

但是我收到了一个错误:

  

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

如何合并列表和当前行?

1 个答案:

答案 0 :(得分:1)

你可能想要这样的东西:

SELECT col1, 
       col2,
       (SELECT col3 FROM Table2 as t2 WHERE t2.id = t1.id) as col3,
       (SELECT col4 FROM Table2 as t2 WHERE t2.id = t1.id) as col4
FROM Table1 as t1

甚至更好:

SELECT t1.col1, 
       t1.col2,
       t2.col3,
       t2.col4
FROM Table1 as t1
JOIN Table2 as t2
  ON t1.id = t2.id

如果您没有要加入两个表的字段,那么:

SELECT t1.col1, 
       t1.col2,
       t2.col3,
       t2.col4
FROM Table1 as t1
CROSS JOIN Table2 as t2