使用临时列左连接

Left join using a temporary column

我想在两个 table 上执行 left join,但第二个 table 没有必填列。 因此,需要一个临时列(第二个 table 中两个列值的连接)才能进行左连接。

select a.name, a.number, b.id, b.sub_num
from tableA a left join
     tableB b
     on a.number = (select concat(id,'-',Cast(sub_num as varchar)) as tempcol from tableB);

显然这显示错误:

SUBQUERY_MULTIPLE_ROWS: Scalar sub-query has returned multiple rows.

但我不需要在主查询中显示此 tempcol,也不需要将其另存为此处任何 table 中的新列。

在临时列上执行左连接的更好方法是什么?

您不需要 join 的子查询。只需使用表达式:

select a.name, a.number, b.id, b.sub_num
from tableA a left join
     tableB b
     on a.number = concat(id, '-', sub_num);

如果愿意,可以使用子查询:

select . . .
from tableA a left join
     (select b.*, concat(id, '-', sub_num) as tempcol
      from tableB b
     ) b
     on a.number = b.tempcol;