如何在Sql中替换Union

如何在Sql中替换Union,sql,sql-server,join,union,Sql,Sql Server,Join,Union,我需要在不使用UNION的情况下将两个表的结果合并。 我有4张桌子a、b、c、d。见以下剪报: 表a: 表b: 表c: 表d: 我使用UNION计算a和d结果,如下所示: select a.id,a.seq,a.item,b.des,c.qty from a left join b on a.item = b.item left join c on a.id = c.id and a.seq = c

我需要在不使用UNION的情况下将两个表的结果合并。 我有4张桌子a、b、c、d。见以下剪报:

表a:

表b:

表c:

表d:

我使用UNION计算a和d结果,如下所示:

            select a.id,a.seq,a.item,b.des,c.qty from a 
                left join b on a.item = b.item
                left join c on a.id = c.id and a.seq = c.seq
            UNION ALL
            select d.id,d.seq,d.item,d.des,c.qty from d
                join c on d.id = c.id and d.seq = c.seq
我的输出:

但我需要相同的结果,而不需要全部使用UNION。
如果可能的话怎么办?

如果您愿意,您可以在(tmp)表中使用INSERT,并在表中获得相同的结果。

您可以应用
完全外部联接
而不是
联合
,后者与
联合
相似

SELECT a.id,a.seq,a.item,b.des,c.qty 
FROM a left join b on a.item = b.item
left join c on a.id = c.id and a.seq = c.seq
FULL OUTER JOIN
(
  SELECT d.id,d.seq,d.item,d.des,c.qty 
  FROM d join c on d.id = c.id and d.seq = c.seq
)x ON a.id = x.id

您可以将
union all
替换为
full join
,使用“false”条件和大量的
COALESCE()
s

逻辑如下所示:

SELECT COALESCE(abc.id, cd.id) as id,
       COALESCE(abc.seq, cd.seq) as seq,
       COALESCE(abc.item, cd.item) as item,
       COALESCE(abc.des, cd.des) as eesc,
       COALESCE(abc.qty, cd.qty) as qty
FROM (SELECT a.id, a.seq, a.item, b.des, c.qty 
      FROM a LEFT JOIN
           b 
           ON a.item = b.item LEFT JOIN
           c
           ON a.id = c.id AND a.seq = c.seq
     ) abc FULL JOIN
     (SELECT d.id, d.seq, d.item, d.des, c.qty 
      FROM d JOIN
           c 
           ON d.id = c.id AND d.seq = c.seq
     ) dc
     ON 1 = 0;  -- never evaluates to true

在上面的查询中存在从表“a”到表“c”(在“id”和“seq”列上)的左联接,在下面的查询中存在从表“d”到表“c”的内部联接。因此,我认为您可以将JOIN从表'c'保留到表'd',它将生成正确的输出

select a.id,a.seq,a.item,b.des,c.qty 
from a 
     left join b on a.item = b.item
     left join c on a.id = c.id and a.seq = c.seq
     left join d on c.id = d.id and c.seq = d.seq;

数据的图像真的不能帮助我们帮助你。花时间以可消费的格式发布;DDL和DML语句。至于你的问题,为什么不能使用
UNION(ALL)
?这似乎是正确的选择。如果没有Union,您只需将所需的行插入临时表并从中进行选择