mysql表連線演算法 如何在MySQL中連線多個表

2021-10-18 03:10:28 字數 2691 閱讀 9619

我需要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

上次查詢執行時間很長,我需要更快的查詢.

最佳答案 我想在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

作為替代方案:

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,用於儲存查詢結果,然後使用上面的查詢.

qtp連線mysql 無驅動 QTP連線MySQL

1 安裝 connector odbc 2 檢視資料來源名稱 控制面板 管理工具 資料來源 odbc 新增 3 連線資料庫 dim conn,connstring 建立資料庫例項 set conn createobject adodb.connection 連線字串 connstring drive...

qtp連線mysql 無驅動 QTP連線MySQL

1 安裝 connector odbc 2 檢視資料來源名稱 控制面板 管理工具 資料來源 odbc 新增 3 連線資料庫 dim conn,connstring 建立資料庫例項 set conn createobject adodb.connection 連線字串 connstring drive...

mysql表連線sql表 MYSQL表連線查詢

表連線查詢 一 交叉連線 笛卡爾積 查詢teacher和course表中所有的資料 select from teacher,course select name,courseid,course.id,cname from teacher,course where teacher.courseid c...