Web程序员的Mysql进阶序三之sql多表数据删除、子查询、联合查询

假设表结构如下:

create table test(
	name varchar(10),
	sex varchar(10)
);
create table test1(
	name varchar(10),
	sex varchar(10)
);

假设多条数据同时插入:

insert into test (name,sex) values('xiao','nan'),('xiao1','nan1'),('xiao2','nan2');
insert into test1 (name,sex) values('xiao','nan'),('xiao1','nan1'),('xiao2','nan2');

多表数据删除:
假设我们需要同时删除两个表中名为xiao的名称的数据,那么:

delete t,t1 from test t,test1 t1 where t.name=t1.name and t.name='xiao'

当然也可以写成:

delete t,t1 from test t,test1 t1 where t1.name='xiao' and t.name='xiao'

子查询:
假设需要在表test中查询test1中同名name的信息的话,那么需要子查询来作为另外一个查询的条件,则代码如下:

select * from test where name in(select name from test1);

联合查询:
假设我需要查询两个表的结果联合在一起,也就是数学上所说的并集,并且不去重,那么就是 union all

select * from test
union all
select *from test1;

得到的结果将会是一个没有去重复的集合,如果去重复:

select * from test
union
select *from test1;
发布了110 篇原创文章 · 获赞 147 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/A757291228/article/details/85179178