如何在MYSQl中合并多个表,它们共有两列

时间:2015-01-23 07:12:07

标签: mysql sql

我有四个表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在所有表中都相同。知道怎么做吗?

3 个答案:

答案 0 :(得分:2)

这可以通过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任何包含任何表的表。

请注意,您不应在实际生产脚本中使用*,请明确使用列名。

答案 1 :(得分:1)

很有可能你不会通过纯粹的比赛得到你想要的结果。例如,以下内容将创建您描述的表:

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;

问题是,如果项目的 ANY 失败,则表示您没有获得一行。您可以考虑使用外连接。

答案 2 :(得分:1)

尽管已经回答了此请求,但我还想为缺失值的情况添加答案,例如:只有鞋子没有给出age_grp /性别对。

对于带连接的解决方案,您需要完全外部连接,MySQL不支持。使用LEFT和/或RIGHT OUTER JOIN模仿这个可能是几个表格的痛苦。

这是使用UNION ALLs和最终聚合的解决方案。

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)会导致语法错误,顺便说一句。我不得不将其更改为CAST(NULL AS UNSIGNED INTEGER)

SQL小提琴:http://www.sqlfiddle.com/#!2/f4fa5c/1