SQL:级联UNION和JOIN [英] SQL: cascade UNION and JOIN

查看:161
本文介绍了SQL:级联UNION和JOIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个桌子之间有一个联合操作符

I have a union opertaion between two tables

SELECT ID_1,
       name_1,
       surname_1,
  FROM T_ONE
 UNION
SELECT ID_2,
       name_2,
       surname_2
  FROM TABLE_2

我想将此UNION操作的结果与另一个表或什至与所有TABLE_1结合.

I want to join the result of this UNION operation with another table or even with all TABLE_1.

如何处理UNION的新表结果.

例如在上一个UNION之后:

RIGHT JOIN TABLE_3
        ON TABLE_3.ID_3 = XXXXXXXXXXXXXXXXXXXX.ID_2

我真的不知道需要输入什么,而不是XXXXXXXXXXXXXXXX来放置UNION生成的新表.

I really do not know what I need to put instead of the XXXXXXXXXXXXXXXX to andle the new table generated by the UNION.

推荐答案

在此处使用派生表,例如"foo",然后根据需要再次联接:

Use a derived table like "foo" here, and then JOIN again however you wish:

SELECT
    *
FROM
    TABLE_3
    LEFT JOIN
    (
    SELECT ID_1, name_1, surname_1, FROM T_ONE
    UNION --ALL would be more efficient if results do not overlap, as van's comment said
    SELECT ID_2, name_2, surname_2 FROM TABLE_2
    ) foo  ON TABLE_3.ID_3 = foo.ID_1

PS.使用LEFT联接:比RIGHT联接少混乱.

PS. Use LEFT joins: less confusing then RIGHT joins.

这篇关于SQL:级联UNION和JOIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆