前言
本章主要讲解mysql的DQl语言第一节·。
mysql基本查询
单表查询
①查询所有:
select * from book;
②查询选中字段记录:
select bname from book;
③条件查询
mysql> select bname from book where s_id<5;
④查询后为字段重命名
select bname as 名字 from book;
⑤模糊查询
%匹配多个字符
select bname as 姓名 from book where bname like '李%';
_匹配一个字符
select bname as 姓名 from book where bname like '李_';
⑥排序(默认升序) order by 以某个字段为主进行排序
select * from bokk order by bid asc;
//升序 asc (asc可以不写)
降序 desc
select * from book order by bid desc;
⑦限制显示数据数量 limit 只接一个数字n时表示显示前面n行
select * from book limit 5
limit 接两个数字m,n时表示显示第m行之后的n行
select * from book limit 2,4;
⑧常用聚合函数
select * from details;
最大值 max
select max(age) from details;
最小值 min
select min(age) from details;
求和 sum
select sum(age) from details;
平均值 avg
select avg(age) from details;
四舍五入 round
select round(avg(age)) from details;
统计 count
mysql> select count(address) from details;
⑨分组查询 group by 筛选条件使用having,having后接条件必须是select后存在的字段
select age,count(age) from details group by age having age>30;
子查询 也叫嵌套查询
mysql> select * from details where age>(select avg(age) from details);
关联查询
①内连接 inner join
无条件内连接 又称笛卡尔连接
select * from book inner join college;
有条件内连接 在无条件基础上on接条件
select * from book inner join college on bid=cid;
②外连接
左外连接 left join
以左表为基准,右表没有对应数据以null填充,多余数据去除
select * from tb1 left join tb2 on id=t_id;
右外连接 right join
以右表为基准,左表没有对应数据以null填充,多余数据去除
select * from tb1 right join tb2 on id=t_id;
== 派生表必须命名 as==
select * from (select * from details where age>30) as a left join student on d_id=s_id;
mysql函数运用
mysql字符串函数:
ASCII(s) | 返回字符串 s 的第一个字符的 ASCII 码。 |
---|---|
CHAR_LENGTH(s) | 返回字符串 s 的字符数 |
CHARACTER_LENGTH(s) | 返回字符串 s 的字符数 |
CONCAT(s1,s2…sn) | 字符串 s1,s2 等多个字符串合并为一个字符串 |
CONCAT_WS(x, s1,s2…sn) | 同 CONCAT(s1,s2,…) 函数,但是每个字符串之间要加上 x,x 可以是分隔符 |
:FIELD(s,s1,s2…) | 返回第一个字符串 s 在字符串列表(s1,s2…)中的位置 |
FORMAT(x,n) | 函数可以将数字 x 进行格式化 “#,###.##”, 将 x 保留到小数点后 n 位,最后一位四舍五入。 |
INSERT(s1,x,len,s2) | 字符串 s2 替换 s1 的 x 位置开始长度为 len 的字符串 |
LOCATE(s1,s) | 从字符串 s 中获取 s1 的开始位置 |
LCASE(s) | 将字符串 s 的所有字母变成小写字母 |
LPAD(s1,len,s2) | 在字符串 s1 的开始处填充字符串 s2,使字符串长度达到 len |
LTRIM(s) | 去掉字符串 s 开始处的空格 |
MySQL 数字函数:
ABS(x) | 返回 x 的绝对值 |
---|---|
ACOS(x) | 求 x 的反余弦值(参数是弧度) |
ASIN(x) | 求反正弦值(参数是弧度) |
ATAN2(n, m) | 求反正切值(参数是弧度) |
AVG(expression) | 返回一个表达式的平均值,expression 是一个字段 |
:FLOOR(x): | 返回小于或等于 x 的最大整数 |
CEIL(x) | 返回大于或等于 x 的最小整数 |
MOD(x,y) | 返回 x 除以 y 以后的余数 |
MIN(expression) | 返回字段 expression 中的最小值 |
LOG10(x) | 返回以 10 为底的对数 |
LOG2(x) | 返回以 2 为底的对数 |
MAX(expression) | 返回字段 expression 中的最大值 |
SUM(expression) | 返回指定字段的总和 |
:SQRT(x): | 返回x的平方根 |
TRUNCATE(x,y) | 返回数值 x 保留到小数点后 y 位的值(与 ROUND 最大的区别是不会进行四舍五入) |
MySQL 日期函数:
ADDDATE(d,n) | 计算起始日期 d 加上 n 天的日期 |
---|---|
ADDTIME(t,n) | 时间 t 加上 n 秒的时间 |
CURDATE() | 返回当前日期 |
CURRENT_DATE() | 返回当前日期 |
CURRENT_TIME | 返回当前时间 |
CURRENT_TIMESTAMP() | 返回当前日期和时间 |
CURTIME() | 返回当前时间 |