【MySQL】的增删改查
一.增
#向表中插入1条数据
1.insert into 表名(字段1,字段2,…) values(值1,值2,…)
#向表中插入多条数据
2.insert into 表名(字段1,字段2,…) values(值1,值2,…), (值1,值2,…),……
#向表中插入来自其他表的数据
3.insert into 表名1(字段1,字段2,…) select (字段1, 字段2, …) from 表名2
二.删
#删除表中所有数据,(表还在)
1.delete from 表名
#按条件删除表中的数据
2.delete from 表名 where name = ‘lincoco’ and age = ‘18’
三.改
update 表名 set name = ‘zg’ where age = ‘19’
四.查
4.1一般查找
1.select * from 表
2.select * from 表 where id > 1
3.select nid,name,age as a from 表 where id > 1
注意:查询时尽量不使用通配符*,而是将字段列出来,这样查询效率会提高。
4.2.按条件查找
and/or/in/not in/between
4.3.模糊查找
where name like ‘lincoco%’ #百分号匹配多个字符
where name like ‘%lincoco’
where name like ‘lincoco_‘ #_下划线匹配一个字符
where name like ‘_lincoco’
4.4 排序
order by 字段 asc #从小到大排
order by 字段 desc #从大到小排
order by 字段1 desc,字段2 asc #首先根据字段1从大到小排,遇到相同时,再按照字段2从小到大排
4.5 limit查找
limit 5 #取结果的前五条数据
limit 5, 6 #取从第5条开始的6条数据
limit 6 offset 5 #取从第5条开始的6条数据
4.6.分组
group by 字段
group by 字段1, 字段2
分组之前的筛选用where,并放在group by 之前,分组之后的筛选,用having,并放在group by 之后。
eg. select username,count(nid) from user WHERE nid>1 GROUP BY username having count(nid)>1;
4.7.跨表查询
select name from t1 where nid in (select nid from t2)
4.8.连表查询
见:1对多 ;多对多
还没有评论,来说两句吧...