我有三个要查询成单个结果的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


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

最佳答案

WHERE
    table_three.part_code IN(
                          ^^


编辑
以下是一些可以满足的替代方法:调整表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);

关于mysql - MySQL Union为两个表,然后合并在第三个表中匹配的位置?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4892358/

10-14 23:01
查看更多