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

时间:2011-02-03 22:14:39

标签: 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

我感谢有人可以提供任何指示。

2 个答案:

答案 0 :(得分:6)

WHERE
    table_three.part_code IN(
                          ^^

修改
以下是满足以下条件的一些备选方案: Gief表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);

带联合的派生表

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);

与联盟的内部联接

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);  

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

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;

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

编辑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);

答案 1 :(得分:0)

尝试这样的事情:)

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;

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;