MySQL--sql语句操作的补充
2019-06-23 21:32 风e逸 阅读(131) 评论(0) 收藏 举报1、增删改查的补充
增:insert into table1(id,name) values(1,'alex'),(3,'abc');
可以同时添加多组数据
将一个表中的数据导入另一个表
insert into t3(name,age) select name,age from t2;
create table t2(
id int auto_increment primary key,
name varchar(32),
age int
)engine = innodb default charset = utf8;
insert into t2(name,age) values('alex',18),('vivid',19);
create table t3(
id int auto_increment primary key,
name varchar(32),
age int
)engine = innodb default charset = utf8;
insert into t3(name,age) select name,age from t2;
删:
delete from tb12;
delete from tb12 where id !=2
delete from tb12 where id =2
delete from tb12 where id > 2
delete from tb12 where id >=2
delete from tb12 where id >=2 or name='alex'
改:
update tb12 set name='alex' where id>12 and name='xx'
update tb12 set name='alex',age=19 where id>12 and name='xx'
查:
查的方式很多,
select * from tb12;
select id,name from tb12;
select id,name from tb12 where id > 10 or name ='xxx';
select id,name as cname from tb12 where id > 10 or name ='xxx';
select name,age,11 from tb12;
其他:
select * from tb12 where id != 1
select * from tb12 where id in (1,5,12);
select * from tb12 where id not in (1,5,12);
select * from tb12 where id in (select id from tb11)
select * from tb12 where id between 5 and 12;
通配符:
select * from tb12 where name like "a%"//%表示,只要是a开头,后面有几个字符都可以
select * from tb12 where name like "a_"//_表示,是以a开头,且后面只能跟一个字符
分页:
用limit
select * from t2 limit 10;表示取前10条
select * from t2 limit 0,10;表示从第0条开始,取10条。
select * from tb12 limit 10 offset 20;
从第20行开始读取,读取10行;
排序:
select * from tb12 order by id desc; 大到小
select * from tb12 order by id asc; 小到大
select * from tb12 order by age desc,id desc;
# 取后10条数据
select * from tb12 order by id desc limit 10;
分组:
select count(id),max(id),part_id from fb12 group by id
count 计数分组
max 取最大值分组
min取最小值分组
sum 求和分组
avg 平均数分组
分组同时想要进行筛选,要用关键字having
连表:
select * from user_bumen,userinfo1,bumen where user_bumen.name_id = userinfo1.id and user_bumen.part_id = bumen.id;
推荐使用:
select * from user_bumen
left join userinfo1 on user_bumen.name_id = userinfo1.id
left join bumen on user_bumen.part_id = bumen.id;
select * from userinfo5 innder join department5 on userinfo5.part_id = department5.id
将出现null时一行隐藏
union,用于连表时,将两个查询结果显示在同一个表内(列数需要相同),自动去重
union all,不去重
select sid,sname from student union select tid,tname from teacher;
输出结果:
+-----+-------+
| sid | sname |
+-----+-------+
| 1 | 钢蛋 |
| 2 | 铁锤 |
| 3 | 山炮 |
| 1 | 波多 |
| 2 | 苍空 |
| 3 | 饭岛 |
+-----+-------+
临时表:
在查询过程中,可能会二次利用到查询结果,因此可以将首次查询结果临时储存,临时储存的文件就叫做临时表。
(select * from course left join teacher on course.teacher_id = teacher.tid) as tem_a;
-- 将查询结果临时存为表 tem_a
浙公网安备 33010602011771号