如何在MySQL中完全外部连接多个表

如何在MySQL中完全外部连接多个表,mysql,join,outer-join,query-performance,Mysql,Join,Outer Join,Query Performance,我需要完全外部联接多个表。我知道如何从中完全外部联接两个表。但是我有好几张桌子,我不能把它用在上面。我怎样才能实现它? 我的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 LEF

我需要
完全外部联接
多个表。我知道如何从中
完全外部联接两个表。但是我有好几张桌子,我不能把它用在上面。我怎样才能实现它?
我的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

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

我认为要对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


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

我执行查询,等待20分钟,然后按取消。)@20分钟真的很高,但我想不出更好的查询;)@谢谢你的回复!!为什么要编写UNION ALL not UNION?对于完整的外部联接
n
表,这个比例如何?