mysql 查询数量、包含关系、排序、分页等操作 - 小白撸代码

时间:2024-03-06 11:42:24

一、查询数量-count()【有多少条数据】

例如:select count(id) count from user where 1 = 1
译:在user表中查询条件满足的数据数量,并以count返回【where类似于if条件】
注:
1、count(*)代表着数据统计的总数。count(id) id 表示查询索引提升查询速度
2、count(id) 后边的 count 是变量,即表示返回数据中的变量 { count: 数量 }
 
二、包含关系-like【包含某些字符】
例如:select * from user where username like \'%xxx%\'
译:在user表中查询username字段中包含xxx的数据
注:
1、%xxx% 查询username字段中包含xxx的记录
2、%xxx 查询username字段中以xxx结尾的记录
3、xxx% 查询username字段中以xxx开头的记录
 
三、数据排序-order by 【对查询的数据排序-asc(升序)-desc(降序)】
例如:select * from user where user_role = 2 order by id asc/desc
译:在user表中查询user_role等于2的数据,并以id排序 【asc:升序,desc:降序】
 
四:分页操作-limit 【语法:limit offset rows】
例如:select * from user where user_role = 2 limit 0 20
译:在user表中,从第1条开始查询,返回20条user_role等于2的数据
注:
1、offset 偏移量(即查询数据库的开始位置)初始值为 0
2、rows 返回数据