select product_id from Products where low_fats = 'Y' and recyclable = 'Y'
select name from customer where referee_id <> 2 or referee_id is null
# 或者
select name from customer where referee_id != 2 or referee_id is null
select name,population,area from World where area >= 3000000 or population >=25000000
select distinct author_id as id from Views where author_id = viewer_id order by author_id
select tweet_id from Tweets where length(content) > 15
左链接的使用
select EmployeeUNI.unique_id,name
from Employees left join EmployeeUNI on EmployeeUNI.id = Employees.id
使用 关联字段相同时使用using 字句
select product_name,year,price
from Sales join Product using(product_id)
使用左连接:A 交 B 的补集,group by 统计
select customer_id,count(*) as count_no_trans
from Visits left join Transactions
using(visit_id)
where Transactions.visit_id is null
group by customer_id
# 利用 AddDate
select w2.id
from Weather w1 cross join Weather w2
on AddDate(w1.recordDate,interval 1 day) = w2.recordDate
where w1.temperature < w2.temperature
# 利用 DateDiff
select w2.id
from Weather w1 cross join Weather w2
on DateDiff(w2.recordDate, w1.recordDate) = 1
where w1.temperature < w2.temperature
平均值的使用,保留 3 位小数
select machine_id,Round(avg(a2.timestamp-a1.timestamp),3) as processing_time
from Activity a1 cross join Activity a2
using(machine_id,process_id)
where a1.activity_type = 'start' and a2.activity_type='end'
group by machine_id
select name,bonus
from Employee left join Bonus
using(empId)
where bonus < 1000 or bonus is null
三表联查
select s.student_id,student_name,su.subject_name,count(e.subject_name) as attended_exams
from Students s join Subjects su left join Examinations e
on e.student_id = s.student_id
and e.subject_name = su.subject_name
group by s.student_id,su.subject_name
order by s.student_id,su.subject_name
嵌套查询,having 的使用
select name
from Employee e1 join (
select managerId
from Employee
group by managerId
having count(managerId) >=5
) as e2
on e2.managerId = e1.id;
思路一:把两个数据分别查出来,然后做除法
思路二:在一个表里面利用 sum(iif)统计出来做除法,还需要配合 convert 和
select user_id,Round(Coalesce(confirm,0)/total,2) as confirmation_rate
from (
select user_id, count(*) as total
from Signups left join Confirmations
using(user_id)
group by user_id
) as t1 left join
(
select user_id,count(action) as confirm
from Confirmations
where action = 'confirmed'
group by user_id
) as t2
using(user_id)