首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL查询优化实践

问SQL查询优化实践
EN

Stack Overflow用户
提问于 2020-09-17 02:42:32
回答 1查看 96关注 0票数 0

我想实践我在小型数据库SQL查询优化方面的技能。我已经创建了一个非常简单的数据库:

​

我用数以千计的条目填充了它,并且需要一些复杂、愚蠢和未优化的查询来进行一些测试和练习我的优化技能。现在,我尝试编写一些查询,但它们对数据库没有太大影响。

我应该使用哪些关键词?有人能帮帮忙吗?

EN

回答 1

Stack Overflow用户

发布于 2020-09-17 04:38:29

我发现很难想出真正糟糕的查询:-)这里有一些想法。希望其他人能想出更多。我建议您将表(空的,甚至包含一些样例行)放在https://dbfiddle.uk/中,我们可以在那里尝试我们的查询。例如,我不知道在下面的查询中是否没有任何语法错误。

查找名为xyz的用户拥有或评论的所有视频:

代码语言:javascript
复制
select distinct v.*
from videos v
left join user_have_videos uv on uv.video_id = v.video_id
left join users u1 on u1.user_id = uv.user_id
left join comments c on c.video_id = v.video_id
left join users u2 on u2.user_id = c.user_id
where u1.user_name = :user_name
   or u2.user_name = :user_name;

查找拥有至少三个不同视频的所有用户:

代码语言:javascript
复制
select distinct u.*
from users u
left join user_have_videos uv1 on uv1.user_id = u.user_id
left join videos v1 on v1.video_id = uv1.video_id
left join user_have_videos uv2 on uv2.user_id = u.user_id
left join videos v2 on v2.video_id = uv2.video_id
left join user_have_videos uv3 on uv3.user_id = u.user_id
left join videos v3 on v3.video_id = uv3.video_id
where v1.video_id <> v2.video_id
  and v1.video_id <> v3.video_id
  and v2.video_id <> v1.video_id
  and v2.video_id <> v3.video_id
  and v3.video_id <> v1.video_id
  and v3.video_id <> v2.video_id;

查找所有评论John Wayne的用户:

代码语言:javascript
复制
select distinct u.*
from users u
join comments c on c.user_id = u.user_id
where lower(comments) like '%john wayne%';

在这里,你会发现这是什么,并让它变得更好:

代码语言:javascript
复制
with cte(user_id, video_id, num) as
(
  select u.user_id, v.video_id, 1
  from videos v
  join user_have_videos uv on uv.video_id = v.video_id
  join users u on u.user_id = uv.user_id
  union all
  select u.user_id, min(v.video_id), min(cte.num) + 1
  from videos v
  join user_have_videos uv on uv.video_id = v.video_id
  join users u on u.user_id = uv.user_id
  join cte on cte.user_id = u.user_id 
           and cte.video_id < v.video_id
  group by u.user_id
)
select distinct u.*
from users u
join cte on cte.user_id = u.user_id and cte.num >= 10;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63926162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档