准备好以下数据
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)
);
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 address where user_id =(select id from user_info where user_name='浅唱灬幸福')#查询叫做'浅唱灬幸福’的数据
select * from address where user_id in (select id from user_info where real_name like '王%')#查询姓王的数据
- 多表查询
- 内连接 取多表中都有的数据
select ui.*,addr.* from user_info ui,address addr where ui.id = addr.user_id
- 外连接: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
根据left和right关键字,left-查询出该关键字左边表的所有数据:right-查询出该关键字右边表的所有数据
- 左连接
- 右连接