mysql是一个小型、开源数据库软件,当今被甲骨文公司收购,但其实用性很强,一般的中小型项目中使用较多。
本篇博客总结部分基础的mysql基础语法的使用,温习学过的知识,提升自己,同时方便以后查阅。
1 增删改查
增加 create table 表名 ( 字段 数据类型,..)
删除 drop table 表名
修改 update 表名 set 字段=修改结果 where 字段=条件
查询 select * from 表名 查询表的所有信息。
2 where与having
where为执行语句增加条件,查询、修改、删除中精确条件使用
如 select * from users where id=11 查询users表中字段id为11的数据
多个并列条件用and连接,或条件or连接。
having 设置函数或筛选条件,查询、修改、删除中多有使用。
如:select * from user where id<10 查询users表中id小于10的数据
3 between 范围操作(标准名称忘记了。)
操作某段范围的数据
如:select * from users where id between 2 and 10 查询users表中id为2和10之间的数据
4 union 将两个sql查询语句的结果合并,去除重复的部分
查询语句1 union 查询语句2 (union all合并两个sql查询语句,不去除重复的部分。)
5 连接查询
左连接(表1为主表):表1 left join 表2 on 表1对象=表2对象 where
多张表时,表1 left join 表2 on 表1对象=表2 left join 表3 on 表2对象=表2 对象 where
右连接(表2为主表):表1 right join 表2 on 表1对象=表2对象 where
完全外连接(表1、表2都是主表。不论有无关系都可查询):表1 full outer join 表2 on 表1对象=表2对象 where
等值连接: 表1 inner join 表2 on 表1对象=表2对象 where ----等于 表1,表2 where 表1对象=表2对象
6 order by 排序,默认升序
如:select id from users order by id 以id为基准,升序排列users表中数据。
order by 对象 desc 降序排列
order by 对象 asc 升序排列
有一个随机排列,没有记录,随机排列效率很低,不建议使用。
7 group by分组
如 select id from users group by name 以name字节对users查询结果分组,用来去除重复数据比较使用。
8 limit (n,m) 获取第n条开始m条数据。常用作分页
如: select * from users order by id limit 2,3 查询users表id升序结果的第二条开始后的三条数据
9 distinct 去重,查询某个表某个字段的数据的去重操作
如:select distinct(name) from users 查询user表中的name,去重name结果一样的数据。去重一般用group by实现
10 函数 sum求和 avg平均值 count条数 max 最大值 min最小值
如select avg(年龄) from users 查询users表中年龄字段的平局值
11 模糊查询like
如select * from users where name like '王%' 查询users表中name字段以王开始的数据
select * from users where name like '%王' 查询users表中name字段以王结束的数据
select * from users where name like '%王%' 查询users表中name字段以包含王的数据
mysql语句中用的最多是查询,又是多张表单的关系让人头大,工作积累经验,学习是个漫长的过程,加油,快乐分享,共同提升。