一张主表 多张辅表的情况下该如何关联数据 并得出结果集?

id为关联外键 所有的查询以辅表数据是否存在为准

主表A

id name type
1 foo 1
2 bar 2
3 test 1
4 tes1 1
5 tes2 1
6 tes3 1
7 tes4 1
8 tes5 1

辅表B

id color
4 1
5 2
6 3

辅表c

id brand
1 44
2 21
3 12

想得到结果如表D

id 7 8 两条数据在辅表中不存在 也就不再显示

id name type color brand
1 foo 1 null 44
2 bar 2 null 21
3 test 1 null 12
4 tes1 1 1 null
5 tes2 1 2 null
6 tes3 1 3 null
阅读 4.3k
4 个回答

a.sql:

use test
drop table if exists a,b,c;
create table if not exists a(id int,name char(50),type int);
create table if not exists b(id int,color int);
create table if not exists c(id int,brand int);
load data infile 'D:\\phpStudy1\\MySQL\\test_sqls\\a.txt' into table a ignore 1 lines;
load data infile 'D:\\phpStudy1\\MySQL\\test_sqls\\b.txt' into table b ignore 1 lines;
load data infile 'D:\\phpStudy1\\MySQL\\test_sqls\\c.txt' into table c ignore 1 lines;
select * from a;
select * from b;
select * from c;
select * from a left join b using(id) left join c using(id) where b.color is not null or c.brand is not null;
drop table if exists a,b,c;

运行结果:

D:\phpStudy1\MySQL\bin>mysql -uroot -proot < D:\phpStudy1\MySQL\test_sqls\a.sql
id      name    type
1       foo     1
2       bar     2
3       test    1
4       tes1    1
5       tes2    1
6       tes3    1
7       tes4    1
8       tes5    1
id      color
4       1
5       2
6       3
id      brand
1       44
2       21
3       12
id      name    type    color   brand
1       foo     1       NULL    44
2       bar     2       NULL    21
3       test    1       NULL    12
4       tes1    1       1       NULL
5       tes2    1       2       NULL
6       tes3    1       3       NULL

图片描述

我一般是不喜欢用联查的,可以分别查出三个表的数据,然后用php的数组加循环来处理,循环的时候你可以判断他们的id相同的话,就加个key把对应的value放进去,这样不就得到你的数据了?

学习一下 left join

使用left join 左连接,以主表为主,副表中没有对应的数据会为空。

SELECT * FROM 表a AS a
LEFT JOIN 表b AS b ON a.id=b.id
LEFT JOIN 表c AS c ON a.id=c.id;

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题