1.限制返回行数
例如返回前两行
- select device_id from user_profile limit 0,2---运行效率更高
- select device_id from user_profile limit 2 ---运行效率低
- 结合 limit offset: 一起使用时,limit表示要取的数量,offset表示跳过的数量
- select device_id from user_profile limit 2 offset 0 // 跳过0条,从第一条数据开始取,取两条数据 ---运行效率中
检索记录行 6-10
SELECT
*
FROM
table
LIMIT 5,5
检索记录行 11-last
SELECT
*
FROM
table
LIMIT 10,-1
2.将年龄划分为25以上和25以下
查询结果:
SELECT IF(age>=25,"25岁及以上","25岁以下") AS age_cut,count(device_id) AS number
FROM user_profile
GROUP BY age_cut;
select
CASE
when age < 25 or age is null then '25岁以下'
when age >= 25 then '25岁以上'
end as age_cut, count(device_id) number
from user_profile
group by age_cut
如果年龄为空,年龄一行设置为其他
select device_id,gender,
case
when age < 20 then '20岁以下'
when age >= 20 and age < 24 then '20-24岁'
when age >= 25 then '25岁及以上'
else '其他'
end as age_cut
from user_profile
3.分别获取日期字段中的年、月、日
年:year(date) = '2021' 或者 date like ('2021%')
月:month(date)
日:day(date)
4.一个字段多种属性
统计每个性别的用户分别有多少参赛者,并且按照人数从小到大排列:
提示:从小到大---asc ,从大到小---desc
select
case
when profile like '%,male' then 'male'
when profile like '%,female' then 'female'
end as gender,
count(device_id) as number
from user_submit
group by gender
order by number asc
5.删除指定字段中的某一部分内容
例如:http:/ur/bisdgboy777 改为 ur/bisdgboy777
- 替换法 replace(string, '被替换部分','替换后的结果')
device_id, replace(blog_url,'http:/url/','') as user_name
- 截取法 substr(string, start_point, length*可选参数*)
device_id, substr(blog_url,11,length(blog_url)-10) as user_nam
- 删除法 trim('被删除字段' from 列名)
device_id, trim('http:/url/' from blog_url) as user_name
- 字段切割法 substring_index(string, '切割标志', 位置数(负号:从后面开始))
device_id, substring_index(blog_url,'/',-1) as user_name
6.找出每个学校GPA最低的同学
结果
select device_id, university,gpa
from user_profile u1
where gpa <= (
select min(gpa)
from user_profile u2
where u1.university = u2.university
group by university
)
order by university asc
7.去重distinct
select university from user_profile group by university
或者
SELECT DISTINCT university from user_profile