SELECTa.name,b.titleFROMauthor AS aLEFT JOINbook AS bON a.id = b.author_idUNIONSELECTa.name,b.titleFROMauthor AS aRIGHT JOINbook AS bON a.id = b.author_id
-- (t1 ∩ t2): all in both t1 and t2select t1.value, t2.valuefrom t1 join t2 on t1.value = t2.valueunion all -- And plus-- all in t1 that not exists in t2select t1.value, nullfrom t1where not exists( select 1 from t2 where t2.value = t1.value)union all -- and plus-- all in t2 that not exists in t1select null, t2.valuefrom t2where not exists( select 1 from t1 where t2.value = t1.value)
-- t1 left join t2SELECT t1.value, t2.valueFROM t1 LEFT JOIN t2 ON t1.value = t2.value
UNION ALL -- include duplicates
-- t1 right exclude join t2 (records found only in t2)SELECT t1.value, t2.valueFROM t1 RIGHT JOIN t2 ON t1.value = t2.valueWHERE t1.value IS NULL
SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.Name = t2.Name;
正确的等价物是:
SELECT t1.*, t2.*FROM (SELECT name FROM t1 UNION -- This is intentionally UNION to remove duplicatesSELECT name FROM t2) n LEFT JOINt1ON t1.name = n.name LEFT JOINt2ON t2.name = n.name;
WITH cte_t1 AS( SELECT 1 AS id1 UNION ALL SELECT 2 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6),cte_t2 AS( SELECT 3 AS id2 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6)SELECT * FROM cte_t1 t1 FULL OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2;
这给了我们这样的答案:
id1 id21 NULL2 NULLNULL 3NULL 45 56 66 66 66 6
UNION解决方案:
SELECT * FROM cte_t1 t1 LEFT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2UNION SELECT * FROM cte_t1 t1 RIGHT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2
给出错误答案:
id1 id2NULL 3NULL 41 NULL2 NULL5 56 6
联合所有解决方案:
SELECT * FROM cte_t1 t1 LEFT OUTER join cte_t2 t2 ON t1.id1 = t2.id2UNION ALLSELECT * FROM cte_t1 t1 RIGHT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2
(SELECT a.* FROM tablea aLEFT JOIN tableb b ON a.`key` = b.keyWHERE b.`key` is null)UNION ALL(SELECT a.* FROM tablea aLEFT JOIN tableb b ON a.`key` = b.keywhere a.`key` = b.`key`)UNION ALL(SELECT b.* FROM tablea aright JOIN tableb b ON b.`key` = a.keyWHERE a.`key` is null);
(SELECT*FROMtable1 t1LEFT JOINtable2 t2 ON t1.id = t2.idWHEREt2.id IS NULL)UNION ALL(SELECT*FROMtable1 t1RIGHT JOINtable2 t2 ON t1.id = t2.idWHEREt1.id IS NULL);
SELECT fieldsFROM firsttableFULL OUTER JOIN secondtable ON joincondition
分为:
SELECT fieldsFROM firsttableLEFT JOIN secondtable ON joinconditionUNION ALLSELECT fields (replacing any fields from firsttable with NULL)FROM secondtableWHERE NOT EXISTS (SELECT 1 FROM firsttable WHERE joincondition)
或者,如果您至少有一列,例如foo,在firsttable中不是NULL,则可以执行以下操作:
SELECT fieldsFROM firsttableLEFT JOIN secondtable ON joinconditionUNION ALLSELECT fieldsFROM firsttableRIGHT JOIN secondtable ON joinconditionWHERE firsttable.foo IS NULL