[英]How to FULL OUTER JOIN multiple tables in MySQL
I need to FULL OUTER JOIN
multiple tables.我需要
FULL OUTER JOIN
多个表。 I know how to FULL OUTER JOIN
two tables from here .我知道如何从这里
FULL OUTER JOIN
两个表。 But I have several tables, and I can't apply it over them.但是我有几张表,我无法将其应用于它们。 How can I achieve it?
我怎样才能实现它?
My SQL code, below:我的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
Also I tried this query:我也试过这个查询:
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
Last query executes very long time, I need faster query.最后一个查询执行很长时间,我需要更快的查询。
I think to have a FULL OUTER JOIN
over 3 tables, you need to do it like this:我认为要对 3 个表进行
FULL OUTER JOIN
,您需要这样做:
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
As an alternative for this:作为替代方案:
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
I suggest you to create some temporary tables like t1
, t2
and t3
for storing results of your queries, then use above query over those.我建议您创建一些临时表,如
t1
、 t2
和t3
来存储查询结果,然后在这些查询上使用上面的查询。
@ shA.t感谢测试中的A + <3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.