狗家sql

本文探讨了SQL查询中常见的优化技巧,包括如何通过检查执行计划来定位瓶颈、使用子查询代替连接、添加索引、选择合适的连接类型等。特别强调了在进行多表连接时的注意事项,以及如何通过调整查询策略提升效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.      dt|user_id|views

1.1.   find active user of the month

select distinct user_id from views
where date_format(dt,’%Y-%m’) = date_format(curdate(),’%Y-%m’) and views > 0;

 

1.2.   find rolling 7 days window active viewer找出每一天,当天最近7天内有浏览过视频的用户

select v1.dt, count(distinct v2.user_id) from views v1
join views v2 on v2.dt > v1.dt - 7 and v2.dt <= v1.dt
where v2.views >0
group by v1.dt
order by v1.dt;

 

Q9 - When joining multiple tables is slow, what do you do?

check execution plan to find out the bottle neck.

We use subquery before join.

Add index;

If we are sure every record in table1 will have a match on table2, we should use inner join instead of left join. 

If we need to use left join, we should always put the smaller table on the right, because for every record on the left side, we need to search through the right table.

Assuming we have 3 tables, table 1 and table 3 are pretty large and table 2 is small. We can join table 1 with table 2 first, and then join table 3 uses t2.id instead of t1.id. This would mean we only pull up rows out of t3 if you have a full match on t1 and t2, so your t2.col1 filter would reduce the number of rows visited in t3.

We can add EXPLAIN at the beginning of any (working) query to get a sense of how long it will take. This is most useful if you run EXPLAIN on a query, modify the steps that are expensive, then run EXPLAIN again to see if the cost is reduced.

转载于:https://www.cnblogs.com/ffeng0312/p/9998907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值