[英]How to combine two tables in MySQL which have only one common column and other are different?
[英]How to merge multiple tables in MYSQl which have two columns in common
我有四個表table_1,table_2,table_3和table_4。 他們四個人都有這樣的列:
table_1: age_grp, gender, height;
table_2: age_grp, gender, weight;
table_3: age_grp, gender, shoesize;
table_4: age_group, gender, BMI;
我想用列創建一個新表:
age_grp, gender, height, weight, shoesize, BMI
我只希望合並所有表中age_grp and gender
相同的列。 任何想法如何做到這一點?
這很容易通過INNER JOIN
:
SELECT table_1.*, table_2.*, table_3.*, table_4.* FROM table_1
INNER JOIN table_2 ON table_1.age_grp = table_2.age_grp
AND table_1.gender = table_2.gender
INNER JOIN table_3 ON table_2.age_grp = table_3.age_grp
AND table_2.gender = table_3.gender
INNER JOIN table_4 ON table_3.age_grp = table_4.age_grp
AND table_3.gender = table_4.gender
如果您要求所有表中的所有數據在列中具有相同的值,則可以將任何表與任何表JOIN
。
請注意,您不應在實際的生產腳本中使用*
,而應顯式使用列名稱。
您很有可能不會通過單純的比賽獲得想要的結果。 例如,以下將創建您描述的表:
insert into newtable
select t1.age_grp, t1.gender, t1.height, t2.weight, t3.shoesize, t4.BMI
from table_1 t1
inner join table_2 t2 on t1.age_grp = t2.age_grp
and t1.gender = t2.gender
inner join table_3 t3 on t1.age_grp = t3.age_grp
and t1.gender = t3.gender
inner join table_4 t4 on t1.age_grp = t4.age_grp
and t1.gender = t4.gender;
問題是,如果任何一項失敗,您將不會獲得任何支持。 您可以考慮使用外部聯接。
盡管此請求已得到答復,但我想為缺少值的情況添加一個答案,例如,僅不為age_grp / gender對給出鞋號。
對於帶有連接的解決方案,您需要MySQL不支持的FULL OUTER JOIN。 而用LEFT和/或RIGHT OUTER JOINs來模仿這一點可能會給多張桌子帶來痛苦。
這是使用UNION ALL和最終聚合的解決方案。
create table mytable as
select age_grp, gender, max(height) as height, max(weight) as weight, max(shoesize) as shoesize, max(bmi) as bmi
from
(
select age_grp, gender, height, cast(null as unsigned integer) as weight, cast(null as unsigned integer) as shoesize, cast(null as unsigned integer) as bmi from table_1
union all
select age_grp, gender, cast(null as unsigned integer) as height, weight, cast(null as unsigned integer) as shoesize, cast(null as unsigned integer) as bmi from table_2
union all
select age_grp, gender, cast(null as unsigned integer) as height, cast(null as unsigned integer) as weight, shoesize, cast(null as unsigned integer) as bmi from table_3
union all
select age_group, gender, cast(null as unsigned integer) as height, cast(null as unsigned integer) as weight, cast(null as unsigned integer) as shoesize, bmi from table_4
) x
group by age_grp, gender;
我很驚訝CAST(NULL AS INT)
導致語法錯誤,btw。 我必須將其更改為CAST(NULL AS UNSIGNED INTEGER)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.