58
SELECT airline, airports.icao_code, continent, country, province, city, website 

FROM airlines 
FULL OUTER JOIN airports ON airlines.iaco_code = airports.iaco_code
FULL OUTER JOIN cities ON airports.city_id = cities.city_id
FULL OUTER JOIN provinces ON cities.province_id = provinces.province_id
FULL OUTER JOIN countries ON cities.country_id = countries.country_id
FULL OUTER JOIN continents ON countries.continent_id = continents.continent_id

它说

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以airports在第 4 行的“airlines.iaco_code = airports.iaco_code full external join”附近使用正确的语法

语法对我来说是正确的。我以前从未做过很多连接,但我需要一个表中的这些列,这些列由各种 id 交叉引用。

4

4 回答 4

91

MySQL中没有FULL OUTER JOIN。见7.2.12。外连接简化12.2.8.1。加入语法

FULL OUTER JOIN您可以使用 UNION进行模拟(从 MySQL 4.0.0 开始):

有两个表 t1,t2:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id

三个表 t1、t2、t3:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
RIGHT JOIN t3 ON t2.id = t3.id
于 2010-03-05T03:06:27.800 回答
16

cletus 的回答不太正确。UNION将删除 aFULL OUTER JOIN将包含的重复记录。如果您需要使用类似的重复项:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
LEFT JOIN t4 ON t3.id = t4.id
UNION ALL
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t2.id = t3.id
LEFT JOIN t4 ON t3.id = t4.id
WHERE t1.id IS NULL
UNION ALL
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
RIGHT JOIN t3 ON t2.id = t3.id
LEFT JOIN t4 ON t3.id = t4.id
WHERE t2.id IS NULL
UNION ALL
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
RIGHT JOIN t3 ON t2.id = t3.id
RIGHT JOIN t4 ON t3.id = t4.id
WHERE t3.id IS NULL;
于 2010-07-28T20:34:07.127 回答
1

我刚刚为此做了一个技巧:

(select 1 from DUAL) d
LEFT OUTER JOIN t1 ON t1.id = t2.id
LEFT OUTER JOIN t2 ON t1.id = t2.id

关键是,来自 dual 的查询是一个固定点,mysql 可以将其他 2 个表外部连接到该点

于 2016-10-05T20:40:37.323 回答
1

只需在需要FULL OUTER JOIN三个表 t1、t2、t3 时补充情况。您可以依次使 t1、t2、t3 左连接其余两个表,然后联合。

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
LEFT JOIN t3 ON t1.id = t3.id
UNION
SELECT * FROM t2
LEFT JOIN t1 ON t2.id = t1.id
LEFT JOIN t3 ON t2.id = t3.id
UNION
SELECT * FROM t3
LEFT JOIN t1 ON t3.id = t1.id
LEFT JOIN t2 ON t3.id = t2.id
于 2018-03-08T06:02:41.637 回答