MySQL联盟为两个表,然后在第三个表中合并匹配?

Wil*_*rth 0 mysql union distinct

我有三个MySQL表,我试图查询到一个结果.尽管我已经接近了这一点,但我认为这是可能的,但是我已经在最后一部分工作方面遇到了障碍.

基本上我有两个表(table_one和table_two),我正在尝试UNION DISTINCT,它完美地运行.当我试图引入第三张表时,它全部爆炸并决定不返回任何东西.我确定这是用户错误:)

这段代码可能没有把所有东西放在正确的位置,因为我正在尝试这样做,所以也许我只需要在正确的方向上稍微推动一下.

SELECT
    part_code,
    name
FROM
    table_three

WHERE
    table_three.part_code = (

    SELECT
        part_code
    FROM
        table_one

    UNION DISTINCT
    SELECT
        part_code
    FROM
        table_two
)

ORDER BY
    name ASC
Run Code Online (Sandbox Code Playgroud)

我感谢有人可以提供的任何方向.

Ron*_*nis 5

WHERE
    table_three.part_code IN(
                          ^^
Run Code Online (Sandbox Code Playgroud)

编辑
以下是满足以下条件的一些备选方案:表3中的所有行,以便零件代码存在于表1或表2中.

select t3.part_code
      ,t3.name
  from table_three t3
 where part_code in(select t1.part_code from table_one t1)
    or part_code in(select t2.part_code from table_two t2);
Run Code Online (Sandbox Code Playgroud)

带联合的派生表

select t3.part_code
      ,t3.name
  from table_three t3
  join (select part_code from table_one 
         union
        select part_code from table_two
       ) t12
     on(t3.part_code = t12.part_code);
Run Code Online (Sandbox Code Playgroud)

内联合与联盟

select t3.part_code
      ,t3.name
  from table_three t3
  join table_one   t1 on(t3.part_code = t1.part_code)
union   
select t3.part_code
      ,t3.name
  from table_three t3
  join table_two   t2 on(t3.part_code = t2.part_code);  
Run Code Online (Sandbox Code Playgroud)

奖金.我不知道为什么我这样做.

select t3.part_code
      ,t3.name
  from table_three t3
  left join (select distinct part_code 
                      from table_one) t1 on(t3.part_code = t1.part_code)
  left join (select distinct part_code 
                      from table_two) t2 on(t3.part_code = t2.part_code)
 where t3.part_code = t1.part_code
    or t3.part_code = t2.part_code;
Run Code Online (Sandbox Code Playgroud)

让我知道他们是如何运作的.

编辑2.
好的,请尝试以下操作.它应该产生表T1和T2的并集.然后对于每一行,如果可以找到这样的零件代码,它将从T3中选择名称.

如果part_code是所有表中的键,则可以UNION ALL改为执行.

select T12.part_code
      ,coalesce(T3.name, T12.name) as name
  from (select part_code, name from table_one T1 union   
        select part_code, name from table_two T2
       ) T12
  left join table_three T3 on(T1.part_code = T3.part_code);
Run Code Online (Sandbox Code Playgroud)