准备:
创建user_info表和address表,并在其中插入数据
#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','吉林长春');
多表查询
多个表关联查询需要依据多表之间列关系将其连接起来,这种连接方式分为三种:内连接(inner join)、外连接(outer join)及交叉连接(cross join)
内连接:
内连接,取多表之间交集
select ui.*,addr.* from user_info ui,address addr where ui.id=addr.user_id
外连接:
根据left和right关键字:left-查询出该关键字左边表的所有数据;right-查询出该关键字右边表的所有数据。
select ui.*,addr.*
from user_info ui
left join address addr on ui.id=addr.user_id
select ui.*,addr.*
from user_info ui
right join address addr on ui.id=addr.user_id
交叉连接:
左表(“cross join”关键字左边的表)中的每一行与右表(“cross join”关键字右边的表)中的所有行组合,交叉联接的结果是一个笛卡尔积。
select ui.*,addr.* from user_info ui cross join address addr;