多个表关联查询需要依据多表之间列关系将其连接起来,这种连接方式分为三种:内连接(inner join)、外连接(outer join)及交叉连接(cross join)【本文不讨论交叉连接,简单了解即可】
数据准备
#user_info表
create table user_info(
id int(2) primary key,
user_name varchar(12) unique,
password varchar(15) not null,
real_name varchar(8) not null,
age int(3)
);
#address表
create table address(
id int(2) primary key,
user_id int(2) not null,
real_name varchar(8),
mobile char(11),
address varchar(150)
);
insert into user_info values(1,'浅唱灬幸福','8912@321','王晓明',12);
insert into address values(1,1,'王小明','15516472282','山西太原');
insert into address values(2,1,'王鑫','18404905139','山西大同');
insert into address values(3,1,'任建','15333021730','山西晋城');
insert into user_info values(2,'ぅ浮生若梦〤','56701wz','王楠',36);
insert into address values(4,2,'王楠','15010303314','北京海淀');
insert into address values(5,2,'赵婕','18435224278','山西长治');
insert into user_info values(3,'街角の风铃','27w4921','李晓飞',9);
insert into address values(6,6,'刘倩','13159775555','吉林长春');
查看表中数据
select * from user_info
select * from address
1.内连接(连接结果取两个表符合连接条件的交集)
演示
select ur.*,addr.* from user_info ur,address addr where ur.id= addr.user_id
可以看见我们找到了user_info表中id值和address表中user_id值相同的数据交集
2.外连接(关键字left right)
演示
select ur.*,addr.*
from user_info ur
left join address addr on ur.id= addr.user_id
此时显示了在user_info表中符合user_info表中id值和address表中user_id值相同的address表中的数据(user_info表中不符合的显示为null)
select ur.*,addr.*
from user_info ur
right join address addr on ur.id= addr.user_id
此时显示了在address表中符合user_info表中id值和address表中user_id值相同的user_info表中的数据(address表中不符合的显示为null)
结论:根据left和right关键字:left指的是查询出该关键字左边表的所有数据;right是查询出该关键字右边表的所有数据;