如何在MySQL中连接多个表

时间:2015-05-28 04:23:38

标签: mysql join outer-join query-performance

我需要 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 个答案:

答案 0 :(得分:2)

我认为有一个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来存储查询结果,然后使用上面的查询。