基础篇
概览
SELECT table.col1, table.col2FROM tableJOIN table2 b on table.col1 = b.col3WHERE b.col3 = ?GROUP BY ??HAVING ??ORDER BY ?? DESCLIMIT m, n
检索数据
- 检索所有数据
- select *
- 检索指定列
- select col1, col2,
- 不同值
- DISTINCT
- DISTINCT id, price 表示id price 都相同才会认为相同
- 限制结果
- limit m,n 从第m行开始,选出n行
- limit n offset m ,从偏移m行的位置开始,选出n行
- 多列排序
- order by col1 desc, col2
- 先按照col1降序,再按照col2升序
- 自定义标签顺序
- order by field(
col, ‘colValue1’, ‘colValue2’) - field(
batch, ‘RT’, ‘T’, ‘R’, ‘L’, ‘N’ )
- order by field(
- order by col1 desc, col2
- 结果过滤
- 不等于 <> !=
- 空 isnull()
- bewteen (a, b) 包含边界的范围
- and or and优先级高于or 推荐总是写上 小括号
- in in会比or更快,容易动态创建
- 通配符 少用
- % 一个或多个
- _单个字符
- MySQL 正则
- 仅支持一部分语法,8版本会有更多语法 但是不常用
- REGEXP()
- | 或者
- [^123] 非
- 转义
- 区别于其他语言。MySQL使用双斜杠
- \n 换行
- \r 回车
- \t 制表符
- 区别于其他语言。MySQL使用双斜杠
- 元字符
- 0或者多个
- 1或者多个
- ? 0或1个
- {n} n个
- {n,} >=n上
- {m,n} m-n 个
- 位置符
- ^ 文本开始
- $ 文本结尾
- [[:<:]] 词首
- [[:>:]] 词尾
计算字段
字符串
- Left()
- Right()
- Length()
- Locate(substr, str)
- 判断子字符串在字符串中出现的位置
- lower() upper()
- Ltrim() Rtrim()
- soundex()
- 日期时间
- Year() Month() Day() Date() Hour() Minute() Time()
- curTime() Now()
- curDate()
- DateDiff()
- Date_add()
- Interval 2 day 时间间隔
- Date_add(now(), Interval -2 day)
- 数值计算
- Abs()
- Rand()
- Ceil()
- Floor()
- Exp()
- Mod() 取余数
- Round () 指定位数的小数 可以取整数
- 聚合函数
- Count()
- count(*) 行数
- count(col) 非空计数 不计NULL
- MAX()
- MIN()
- SUM()
- Count()
- 分组函数
- Group BY()
组合查询
清空
- truncate table
- 插入多条
- insert into table(col1, col2, col2) values(‘col1’, ‘col2’, ‘col3’),(‘cola’, ‘colb’, ‘colc’)
- select 与 insert into的结合
- insert into table(col1, col2, col3) select col1, col2, col3 from table_select
- 少了关键字 values
- 从table_select中检索数据直接插入table,
- 实际上不关心列名,只关心列的顺序
- insert into table select * from table_select
- 或者都指定列名,或者都不指定列名
- 错误的写法:insert into table(col1, col2, col2) select * from …
- insert into table(col1, col2, col3) select col1, col2, col3 from table_select
更新删除
虚拟的表
- 使用时动态检索
- 隐藏、复用SQL
- 通常用来检索而非更新数据
涉及分组、联接、子查询、并集、聚合函数、DISTINCT等,不能进行视图更新(不能正确确定基数据)
存储过程
一般的存储过程
create procedure ordertotal(IN onumber INT,OUT ototal DECIMAL(8,2))BEGINSELECT Sum(item_price*quantity)From orderitemsWhere order_num = onumberINTO ototal;END
参数
- IN 传入参数,需要指定格式
- OUT 输出参数,需要指定格式
- 内部使用的变量 需要先严格声明
- 调用存储过程
- CALL(20005, @total);
- 入参 20005
- 出参 @total 所有MySQL变量都必须以@开始
- CALL(20005, @total);
- 存储过程+临时表 输出复杂表格
```
