题单:高频 SQL 50 题(基础版) - 学习计划 - 力扣(LeetCode)全球极客挚爱的技术成长平台
查询:
'且'条件查询:
sql
select product_id from Products where low_fats='Y' and recyclable='Y';
空值判定:
sql
SELECT name FROM Customer where referee_id !=2 OR referee_id is NULL;
'或'条件查询
sql
select name,population,area from World where area>=3000000 or population>=25000000;
查询视图列别名、排序
sql
select distinct(author_id) as 'id' from Views where author_id=viewer_id order by author_id asc;
字段长度
sql
select tweet_id from tweets where length(content)>15;
连接:
两表左值连接:
sql
select unique_id,name from employees left join employeeUNI on employees.id=employeeUNI.id;
两表内连接(两表字段组合):
此题也可用左值连接,因为两表存在外键约束,不会出现null
sql
select Product.product_name, Sales.year, Sales.price
fromSales
join Product
on Sales.product_id = Product.product_id;
两表左值连接后在子视图中查询,并根据customer_id分组,最后计数
sql
select customer_id,count(customer_id) as count_no_trans
from Visits
left join transactions using(visit_id)
where transactions_id is null
group by customer_id;
单表内连接(笛卡尔积)
sql
select a.id
from weather as a
inner join weather as b
on datediff(a.recordDate, b.recordDate) = 1
where a.Temperature > b.Temperature;
单表内连接、聚合函数
1.先内连接找到同一组机器的同一个进程,并按机器分组聚合
2.然后使用聚合函数avg求每组的平均数,并起别名
sql
select t1.machine_id,round(avg(t2.timestamp-t1.timestamp),3) as processing_time
from activity as t1,activity as t2
where t1.machine_id=t2.machine_id
and t1.process_id=t2.process_id
and t1.activity_type='start'
and t2.activity_type='end'
group by t1.machine_id
两表左外连接(需要左表全部数据)
select Employee.name,Bonus.bonus from
Employee left join Bonus using(empId)
where Bonus.bonus<1000 or Bonus.bonus is null;
三表笛卡尔积、左外连接、聚合函数
注意:非聚合列(出现在查询语句中,但未被聚合函数处理)必须出现在group by语句中
sql
select
Students.student_id,
Students.student_name,
Subjects.subject_name,
COUNT(Examinations.subject_name) as attended_exams
from
Students cross join Subjects left join Examinations
on
Students.student_id = Examinations.student_id
and Subjects.subject_name = Examinations.subject_name
group by
Students.student_id,
Students.student_name,
Subjects.subject_name
order by
Students.student_id,
Subjects.subject_name;
单表左值连接,使用HAVING在数据已经被分组后,对分组的结果进行筛选。
sql
select a.name
from
Employee as a left join Employee as b
on
a.id=b.managerId
group by a.id
having count(b.id)>=5;
round函数,IFNULL函数,avg聚合函数。
sql
# Write your MySQL query statement below
select
s.user_id, round(IFNULL(AVG(c.action='confirmed'), 0), 2) AS confirmation_rate
from
Signups as s left join Confirmations as c
on s.user_id=c.user_id
group by s.user_id;
mod聚合函数
sql
select * from cinema
where description != 'boring' and mod(id,2)=1
order by rating desc;