使用mysql联接的两个表的并集出现重复列错误

sqxo8psd  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(355)

我有两张table,如下:

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 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
a11xaf1n

a11xaf1n1#

您需要重命名其中一个 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
z9smfwbn

z9smfwbn2#

通常,你会用一个 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 join 以及 right join . 这有点类似于 full join 在某些情况下。但是,它比这些方法的性能更为密集,并且与实际的 full join 可能很难理解(和纠正)。

相关问题