与JOINS MySQL的两个表的UNION上的重复列错误

时间:2018-11-23 15:15:25

标签: mysql sql

我有两个表,如下所示:

CREATE TABLE NameWithAddress
  ( 
    Name                    VARCHAR(255),
    Address                 VARCHAR(255)
  ); 

  CREATE TABLE NamesWithCountry
  ( 
    Name                   VARCHAR(255),
    Country                VARCHAR(255)
  );

我想合并两个表,因此名称上匹配的行会被合并,但查询中仍会包含两个表中不匹配的行

我有一个查询,该查询返回我想要的结果:

SELECT *
FROM `NameWithAddress`
LEFT OUTER JOIN `NamesWithCountry` ON `NameWithAddress`.`Name` = `NamesWithCountry`.`Name`
UNION SELECT *
FROM `NameWithAddress`
RIGHT OUTER JOIN `NamesWithCountry` ON `NameWithAddress`.`Name` = `NamesWithCountry`.`Name`
WHERE `NameWithAddress`.`Name` IS NULL

但是当我尝试选择此查询的结果时,出现重复的列错误。这就是我执行SELECT的方式:

SELECT T.* FROM (
SELECT *
FROM `NameWithAddress`
LEFT OUTER JOIN `NamesWithCountry` ON `NameWithAddress`.`Name` = `NamesWithCountry`.`Name`
UNION SELECT *
FROM `NameWithAddress`
RIGHT OUTER JOIN `NamesWithCountry` ON `NameWithAddress`.`Name` = `NamesWithCountry`.`Name`
WHERE `NameWithAddress`.`Name` IS NULL) T

2 个答案:

答案 0 :(得分:1)

您需要重命名Name列之一或将其忽略:

SELECT T.* FROM (
SELECT `NameWithAddress`.*, `NamesWithCountry`.`Country`
FROM `NameWithAddress`
LEFT OUTER JOIN `NamesWithCountry` ON `NameWithAddress`.`Name` = `NamesWithCountry`.`Name`
UNION SELECT `NameWithAddress`.*, `NamesWithCountry`.`Country`
FROM `NameWithAddress`
RIGHT OUTER JOIN `NamesWithCountry` ON `NameWithAddress`.`Name` = `NamesWithCountry`.`Name`
WHERE `NameWithAddress`.`Name` IS NULL) T

答案 1 :(得分:1)

通常,您可以使用full join来执行此操作,但是MySQL不支持FULL JOIN。我建议:

SELECT n.name, nwa.address, nwc.country
FROM (SELECT Name
      FROM NameWithAddress
      UNION   -- on purpose to remove duplicates
      SELECT Name
      FROM NamesWithCountry
     ) n LEFT JOIN
     NameWithAddress nwa
     ON nwa.name = n.name LEFT JOIN
     NamesWithCountry nwc
     ON nwc.name = n.name;

如果您知道在任何一个表中都绝不重复名称,那么:

select name, max(address) as address, max(country) as country
from ((select name, address, null as country
       from namewithaddress
      ) union all
      (select name, null as address, country
       from namewithcountry
      )
     ) n
group by name;

我强烈反对将unionleft joinright join一起使用。在某些情况下,这与full join近似。但是,与这些方法相比,它的性能更为密集,与实际full join的细微差别可能很难弄清(并纠正)。