力扣算法题:601. 体育馆的人流量
今天在刷算法题时,试用了with,发现性能上还不如直接查询
# Write your MySQL query statement below
explain with s as (
select *
from Stadium
where people >= 100
)
select distinct s1.*
from s s1, s s2, s s3
where
(s1.id = s2.id-1 and s2.id = s3.id-1) or
(s1.id = s2.id+1 and s1.id = s3.id-1) or
(s1.id = s2.id+1 and s2.id = s3.id+1)
order by visit_date
## 力扣中,两个代码不能同时运行,需要注释处理,提交时记得去除explain
explain select distinct s1.*
from Stadium as s1, Stadium as s2, Stadium as s3
where
(s1.people >= 100 and s2.people >= 100 and s3.people >= 100) and
(
(s1.id = s2.id-1 and s2.id = s3.id-1) or
(s1.id = s2.id+1 and s1.id = s3.id-1) or
(s1.id = s2.id+1 and s2.id = s3.id+1)
)
order by visit_date
然后觉得很奇怪,使用explain进行性能测试
发现底层上完全相同,with自是对SQL语句做了一层封装方便调用,调用几次就会查询几次
总结:
with唯一的作用就是封装,将代码进行封装,在多次重复调用相同代码的时候或在进行多次子查询时能将SQL语句抽离出来,使得代码更加简洁明了。
但对于没有使用过with的人来说,会提升代码阅读的难度