如何在 MySQL 中 FULL OUTER JOIN 多个表

Posted

技术标签:

【中文标题】如何在 MySQL 中 FULL OUTER JOIN 多个表【英文标题】:How to FULL OUTER JOIN multiple tables in MySQL 【发布时间】:2015-08-10 09:51:21 【问题描述】:

我需要FULL OUTER JOIN 多个表。我知道如何FULL OUTER JOIN 来自here 的两个表。但是我有几张桌子,我不能在它们上面应用它。我怎样才能实现它? 我的 SQL 代码,如下:

INSERT INTO table
(
  customer_id
 ,g01
 ,g02
 ,g03
 ,has_card
 ,activity
  )
  SELECT sgd.customer_id, sgd.g01,sgd.g02,sgd.g03,sc.value, a.activity
  FROM s_geo_data sgd
  LEFT JOIN s_category sc
  ON sc.customer_id = sgd.customer_id
    UNION
  SELECT sgd.customer_id, sgd.g01,sgd.g02,sgd.g03,sc.value, a.activity
  FROM s_geo_data sgd
  RIGHT JOIN s_category sc
  ON sc.customer_id = sgd.customer_id

    UNION

  SELECT sgd.customer_id, sgd.g01,sgd.g02,sgd.g03,sc.value, a.activity
  FROM s_geo_data sgd
  LEFT JOIN s_activity a
  ON a.customer_id = sgd.customer_id
    UNION
  SELECT sgd.customer_id, sgd.g01,sgd.g02,sgd.g03,sc.value, a.activity
  FROM s_geo_data sgd
  RIGHT JOIN s_activity a
  ON a.customer_id = sgd.customer_id

我也试过这个查询:

INSERT INTO reportls.table
(
  customer_id
 ,g01
 ,g02
 ,g03
 ,has_card
 ,activity
  )
  SELECT sgd.customer_id, sgd.g01,sgd.g02,sgd.g03,sc.value, a.activity
  FROM s_geo_data sgd
  LEFT JOIN s_category sc
  ON sc.customer_id = sgd.customer_id
  LEFT JOIN s_activity a
  ON sc.customer_id = sgd.customer_id

    UNION

  SELECT sgd.customer_id, sgd.g01,sgd.g02,sgd.g03,sc.value, a.activity
  FROM s_geo_data sgd
  LEFT JOIN s_category sc
  ON sc.customer_id = sgd.customer_id
  RIGHT JOIN s_activity a
  ON a.customer_id = sgd.customer_id

    UNION

  SELECT sgd.customer_id, sgd.g01,sgd.g02,sgd.g03,sc.value, a.activity
  FROM s_geo_data sgd
  RIGHT JOIN s_category sc
  ON sc.customer_id = sgd.customer_id
  LEFT JOIN s_activity a
  ON a.customer_id = sgd.customer_id

最后一个查询执行时间很长,我需要更快的查询。

【问题讨论】:

【参考方案1】:

我认为有一个FULL OUTER JOIN 超过 3 个表,你需要这样做:

SELECT t1.value, t2.value, t3.value
FROM t1 LEFT JOIN t2 ON t1.value = t2.value
        LEFT JOIN t3 ON t1.value = t3.value
UNION ALL
SELECT t1.value, t2.value, t3.value
FROM t2 LEFT JOIN t1 ON t1.value = t2.value
        LEFT JOIN t3 ON t2.value = t3.value
WHERE t1.value IS NULL
UNION ALL
SELECT t1.value, t2.value, t3.value
FROM t3 LEFT JOIN t1 ON t1.value = t3.value
        LEFT JOIN t2 ON t2.value = t3.value
WHERE t1.value IS NULL AND t2.value IS NULL

作为替代方案:

SELECT t1.value, t2.value, t3.value
FROM t1 FULL OUTER JOIN t2 ON t1.value = t2.value
        FULL OUTER JOIN t3 ON t1.value = t3.value

我建议您创建一些临时表,如 t1t2t3 来存储查询结果,然后使用上述查询。

【讨论】:

我执行您的查询,等待 20 多分钟,然后按取消。 )) @ШыназАлиш 20 分钟真的很高,但我想不出更好的查询 ;)。 @感谢您的回复!! 为什么要写 UNION ALL 而不是 UNION 对于 FULL OUTER JOINing n 表来说,这如何扩展?

以上是关于如何在 MySQL 中 FULL OUTER JOIN 多个表的主要内容,如果未能解决你的问题,请参考以下文章

如何在 MySQL 中进行 FULL OUTER JOIN?

如何在 MySQL 中 FULL OUTER JOIN 多个表

MySQL:FULL OUTER JOIN - 如何合并一列?

oracle的full outer join如何排除掉空值

在 MySQL 中执行 FULL OUTER JOIN 查询时出错 [重复]

MySQL中没有FULL OUTER JOIN的处理