Linux中MySQL数据库的使用④-----常用查询语句、常用函数

一、常用的查询语句

1.SELECT:字段表达式

select既可以做查询,也可以做输出

select rand();  -- 输出随机数
select unix_timestamp();  -- 显示Unix时间戳
select id, name from student;
2.FROM子句

语法:select 字段 from 表名

FROM后面是数据源,数据源可以写多个,数据源一般是表名,也可以是其他查询的结果

select student.name, score.math from student, score;
3.WHERE子句:按指定条件过滤

语法:select 字段 from 表名 where 条件;
WHERE是做条件查询,只返回结果为True的数据

#将student表中city=陕西的name值查找出来
select name fron student where city='陕西';

空值判断:is null | is not null

select name from student where description is null;
select name from student where description is not null;

范围判断:between …and … | not between … and …

#查询score表中math值位于60~70之间的id和math
select id, math from score where math between 60 and 70;

#查询score表中math值不在60~70之间的id和math
select id, math from score where math not between 60 and 70;

#查询score表中math值大于等于80并且english值小于等于60的数据
select * from score where math>=80 and english<=60;
4.HAVING

HAVING和WHERE功能类似,都可以用来实现条件查询,很多情况下可以用where或者having,甚至可以混合使用。

select name, birthday from student where birthday > '1995-1-1';
select name, birthday from student having birthday > '1995-1-1';
select * from student where id>=3 and city='西安';
select * from student having id>=3 and city='西安';
select * from student where id>=3 having city='西安';

where和having的区别:
只能用是where的情况

select name, birthday from student where id > 2;

#报错。having的条件查询,只能包含在前面的搜索结果里
select name, birthday from student having id >2;

只能使用having的情况

select name as n, birthday as b, id as i from student having i > 2;

#报错。where的条件查询只识别存在的字段
select name as n, birthday as b, id as i from student where i > 2;

having后面可以跟聚合函数,where不行。

select city, min(birthday) from student group by city having min(birthday)>='1996';
5.GROUP BY:分组查询

按照某一字段进行分组,会把该字段中值相同的归为一组,将查询结果分类显示。
如果有where要放在where的后面
语法:select 字段 from 表名 group by 分组字段;

select sex, count(id) from student group by sex;

#在group将需要的结果通过聚合函数拼接
select sex, group_concat(name) from student group by sex;
6.ORDER BY:按字段排序

ORDER BY主要作用是排序
ORDER BY写在GROUP BY后面,如果有having也要写在having后面
语法:select 字段 from 表名 order by 排序字段 asc|desc;
升序asc 降序desc 默认asc

select * from student order by age;
select * from student order by age desc;
7.LIMIT:限制取出数量
#从第1行到m行
select 字段 from 表名 limit m;
#从第m行开始,往下取n行
select 字段 from 表名 limit m, n;
#跳过前n行,取后面的m行
select 字段 from 表名 limit m offset n;  
8.DISTINCT:去重
select distinct city from student;

二、函数

聚合函数
Name Description
AVG() 返回平均值
COUNT() 计数
GROUP_CONCAT() 返回连接的字符串
MAX() 返回最大值
MIN() 返回最小值
SUM() 返回总和
数值计算类函数
NAME Description
ABS(x) 返回x的绝对值
CEIL(x) 返回大于x的最大整数值
FLOOR(x) 返回小于x的最大整数值
MOD(x, y) 返回x/y的模
RAND() 返回0到1内的随机值
ROUND(x, y) 返回参数x的四舍五入的有y位小数的值
TRUNCATE(x, y) 返回数字x截断为y位小数的结果
日期时间相关
NAME Description
NOW() 返回现在的日期时间
DATEDIFF(x, y) 返回起始时间x和结束时间y之间的天数

猜你喜欢

转载自blog.csdn.net/weixin_43670190/article/details/108591746