SQL刷题

数据库SQL查询语句的执行顺序是怎么样的?_sql查询顺序-CSDN博客

注意

where和having

“Where”是一个约束声明,在查询数据库的结果返回之前对数据库中的查询条件进行约束,即在结果返回之前起作用,且where后面不能使用“聚合函数”;

“Having”是一个过滤声明,所谓过滤是在查询数据库的结果返回之后进行过滤,即在结果返回之后起作用,并且having后面可以使用“聚合函数”。

  • 使用的角度:

    • where后面之所以不能使用聚合函数是因为where的执行顺序在聚合函数之前,

      如下面这个sql语句:

      1
      select  sum(score) from student  group by student.sex where sum(student.age)>100;
    • having既然是对查出来的结果进行过滤,那么就不能对没有查出来的值使用having,

      如下面这个sql语句:

      1
      select  student.id,student.name from student having student.score >90;

在查询过程中聚合语句(sum,min,max,avg,count)要比having子句优先执行,而where子句在查询过程中执行优先级别优先于聚合语句(sum,min,max,avg,count)。
简单说来:
where子句:

1
select sum(num) as rmb from order where id>10

//只有先查询出id大于10的记录才能进行聚合语句

升序降序

升序:asc(ascend)

降序:desc(descend)

Union

[sql语句中union的用法_sql union-CSDN博客](https://blog.csdn.net/weixin_42383680/article/details/119858753?ops_request_misc=%7B%22request%5Fid%22%3A%22172242275016800222833310%22%2C%22scm%22%3A%2220140713.130102334..%22%7D&request_id=172242275016800222833310&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-119858753-null-null.142^v100^pc_search_result_base8&utm_term=SQL union&spm=1018.2226.3001.4187)

union联合的结果集不会有重复值,如果要有重复值,则使用union all

union会自动压缩多个结果集合中重复的结果,使结果不会有重复行,union all 会将所有的结果共全部显示出来,不管是不是重复。

union:会对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序。

union all:对两个结果集进行并集操作,包括重复行,不会对结果进行排序。

count

[SQL中COUNT()函数的用法_sqlcount函数的使用方法-CSDN博客](https://blog.csdn.net/fdggdg/article/details/118757777?ops_request_misc=%7B%22request%5Fid%22%3A%22172242334216800211564239%22%2C%22scm%22%3A%2220140713.130102334..%22%7D&request_id=172242334216800211564239&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-118757777-null-null.142^v100^pc_search_result_base8&utm_term=sql count&spm=1018.2226.3001.4187)

177. 第N高的薪水

注意声明函数,变量,set的过程,limit的用法,distinct的用法。

这里变量不能直接N-1带进去,必须重新声明一个变量。

1
2
3
4
5
6
7
8
9
10
11
12
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M = N-1;
RETURN (
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT M, 1
);
END

180.连续出现的数字

1
2
3
4
5
6
select distinct l1.num as ConsecutiveNums
from Logs l1,Logs l2,Logs l3
where
l1.id=l2.id-1
and l1.num=l2.num
and l1.id=l3.id-2 and l1.num=l3.num

602.好友申请②:谁有最多的好友

1
2
3
4
5
6
7
# Write your MySQL query statement below
select id,num from
(select ids as id,count(ids) as num from
(select requester_id as ids from RequestAccepted
union all
select accepter_id as ids from RequestAccepted )as table1 group by ids)as table2
order by num desc limit 0,1;