MYSQL必知必会

MYSQL必知必会

基础

去除重复数据
1
select distinct vend_id from products;
限制返回的行数
1
2
# 要检索的开始行和行数
select name from products limit 5, 5;
按列排序
1
2
3
# 升序 ASC  降序 DESC
select id, price, name from products order by price DESC, name ASC;
select price from products order by price DESC limit 1;
过滤数据
1
2
3
4
select id, name from products where id != 1003;
select name from products where price is NULL;
select name, price from products where price between 5 and 10;
select name, price from products where id in (1002, 1003) order by name;
通配符过滤
1
2
3
4
5
6
# %表示任何字符出现任意次数
select id, name from products where name like '%jet%';
# 注意NULL%无法匹配值为NULL的行
select name from products where name like '%';
# _只匹配单个字符
select id, name from products where name like '_ton';
正则表达式搜索

使用like操作符时,如果不带通配符,则将匹配整个列的值,如果被匹配的文本只是列值的一部分,则不会返回行

相反,使用regexp操作符时,可以匹配列值中的任意部分

1
2
3
4
5
select name from products where name regexp '1000';
# 进行OR匹配
select name from products where name regexp '1000|2000';
# 匹配特定字符
select name from products where name regexp '[123]Tom';
创建计算字段
1
2
3
4
5
6
# 拼接多个列
select concat(name, '(', country, ')') from products;
# 执行算术计算 (+-*/)
select id, quantity*price as expanded_price from orders;
# 测试计算 (省略from子句)
select now();
数据处理函数
文本处理函数
函数 说明
Left(expression, length) 返回串左边的字符
Length() 返回串的长度
Locate(substr, str, start) 返回字串的位置(从1开始算)
Lower()、Upper() 将串转为小写或大写
LTrim()、RTrim()、Trim() 去除串左右空格
Right(expression, length) 返回串右边的字符
Soundex() 返回串的SOUNDEX值(进行发音比较)
SubString(str, start, length) 返回子串(start从1开始)
日期处理函数
函数 说明
AddDate(date, interval expr unit) 增加一个日期
CurDate()、CurTime() 返回当前日期或时间
Date() 返回日期时间的日期部分
Date_Format(date, pattern) 返回一个格式化的日期或时间串
Day()、Year()、Month() 返回日期的部分
Now() 返回当前日期和时间
DateDiff(expr1, expr2) 计算两个日期之差
1
2
3
4
5
6
# use adddate
select adddate(orderdate, interval 10 day), orderdate from orders;
# use date_format
select date_format(orderdate, '%Y/%m/%d') from orders;
# use datediff 天数之差
select datediff('2017/08/25', '2017/08/20');
数值处理函数
函数 说明
Abs() 返回绝对值
Cos()、Sin()、Tan() 返回角度的余弦、正弦、正切
Exp() 返回数的指数值
Mod(num1, num2) 返回除操作的余数
Pi() 返回圆周率
Rand() 返回随机数
Sqrt() 返回数的平方根
Round() 四舍五入

MYSQL必知必会
http://xrcol.github.io/2024/04/05/78e8979df787/
作者
XR
发布于
2024年4月5日
许可协议