背景:
最近想复习一下数据库相关的一些命令或知识,为后续排查故障提供有力的支持,所以从leetcode上找到高频50道sql题进行复习,这里记录一下而已。
题目如下:
1. 使用like进行通配符(wildcard)进行匹配
一般只能用于文本字段或字符串,非文本数据类型不能使用通配符搜索。
% 表示任何字符出现任意次数,也就是能匹配0个、1个或多个字符
例如 "Fish%" 代表以 "Fish"开头的字符串都会被匹配
"%Fish%" 代表 字符串包含Fish的都会被匹配
_ 表示只匹配单个字符而不是多个字符
\] 表示用来指定一个字符集,必须匹配指定位置(通配符的位置)的一个字符 例如 "\[JM\]%" ,其中\[JM\]匹配任何以方括号中的字母开头的字符串 "\[\^JM\]%" ,其中\^用于取反,即 非J或者非M的字母开头的字符串。 620. 有趣的电影 // like 或 not like select * from cinema where cinema.id % 2 = 1 and cinema.description not like '%boring%' order by rating desc; // 使用mod进行取余 select * from cinema where mod(id,2) = 1 and cinema.description not like '%boring%' order by rating desc; #### 2. 聚合函数 // 1211. 查询结果的质量和占比 select query_name, round(avg(rating/position),2) as quality, round(sum(if(rating<3,1,0))*100 / count(*),2) as poor_query_percentage from Queries where query_name is not null group by query_name; // 1075 select project_id, round(avg(experience_years),2) as average_years from Project as p left join Employee as e on p.employee_id = e.employee_id group by project_id; // 1633. 各赛事的用户注册率 select contest_id, round(count(Register.user_id)*100/(select count(*) from Users),2) as percentage from Register group by contest_id order by percentage desc,contest_id asc; 解析: select count(*) from Users // 计算Users表中有多少行,这里是有多少个用户,在这里相当于是一个定值,固定值,整形数值 count(Register.user_id)*100/(select count(*) from Users) // 对group by进行分组后的逻辑小组进行计算,这里得出用户的注册率 round(xxx,2) // 对 xxx 进行保留两位小数 group by contest_id // 对 contest_id进行分组,进而对小组内的内容进行统计和分析 order by percentage desc,contest_id asc // 对结果集进行排序,以percentage进行倒序,如果注册率相同再以contest_id进行正序排序 #### 3. order by **order by 子句的位置:应该保证它是select语句中最后一条语句。如果它不是最后的子句,将会出现错误消息,主要分为单个列排序和多个列排序** 要按多个列排序,简单指定列名,列名之间用逗号分开即可,类似选择多个列时那样,类似于上一个题1633.各赛事的用户注册率 order by percentage desc,contest_id asc 重要的是理解在按多个列排序时候,排序的顺序完全按照规定进行,对于上述例子中的输出,列出多个行具有相同的percentage值时才对contest_id进行排序。 如果是升序排序,可以省略asc;如果是降序排序,需要指定 desc关键字。 **这里注意了: 所以 如果想在多个列上降序排序,必须对每一列指定 desc关键字。这里和 distinct关键字恰恰相反。** #### 4. group by [我记不住的数据库Group BY使用-CSDN博客](https://kermitliu.blog.csdn.net/article/details/47131105 "我记不住的数据库Group BY使用-CSDN博客") ``` select 类别, SUM(数量)from A where 数量 > 8 group by 类别 having SUM(数量) > 10 ``` 先通过where进行过滤行,数量\>8的行被选择,然后进行分组,将同类别的数量和\>10的分组被选择。 // 2356. 每位教师所教授的科目种类的数量 select teacher_id,count(distinct subject_id) as cnt from Teacher group by teacher_id // 1193. 每月交易 I select date_format(trans_date,'%Y-%m') as month, country, count(*) as trans_count, count(if(state='approved',1,NULL))as approved_count, sum(amount)as trans_total_amount, sum(if(state='approved',amount,0))as approved_total_amount from Transactions group by month,country count和if sum和if if(state='approved',amount,0) 如果state等于approved,返回amount,否则为0 // 1729. 求关注者的数量 select user_id,count(follower_id) as followers_count from Followers group by user_id order by user_id // 596. 超过5名学生的课 select class from Courses group by class having count(*)>=5