0

新手求问一个简单的查询优化问题。

 2 years ago
source link: https://www.v2ex.com/t/831251
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  MySQL

新手求问一个简单的查询优化问题。

  natsukage · 1 天前 · 738 次点击

一张表里存储了用户的 ID 和物品的种类、细节、时间,
可以类比为这样的场景
一个表里储存了所有玩家的出货记录,记录了玩家的 ID 、出货的具体物品、物品的品级。
然后我现在想要查询所有玩家的欧皇榜,就是查询每个玩家在一段时间内的总共抽奖次数、5 星物品出货次数与出货率。

因为我完全是 SQL 新手…想了半天最后是用 2 条语句依次进行了 2 次查询。一次是只查询 rType=5 并 count()取得所有人的 5 星出货次数,一次是查询全部并 count()取得全部出货次数,然后两者相除。

select ID,rType,rCount,
TotalCount, temp.rCount/temp2.TotalCount as rRate from(
    select ID,rType,count(*) rCount from item_list
	where rType=5 and CreateDate>=@StartDate and CreateDate<@EndDate
	group by ID,rType
) temp,(
    select ID ID2 ,count(*) TotalCount from item_list
	where CreateDate>=@StartDate and CreateDate<@EndDate
	group by ID
) temp2 where temp.ID = temp2.ID2
order by temp.rType desc,rareRate desc

目前这条语句可以正常工作,但是显然,两次查询查的都是同一个表,而且第一次查询的 temp 其实就只是 temp2 的查询加上了一个 rType=5 的限制条件。

所以想问,这种情况的查询,是不是应该有更好的办法,只对原表一次查询,就获取到我需要的全部信息呢?还是说这种情况本身就应该需要对原表 2 次不同的查询(我感觉应该不会吧…)
多谢指导!

表的内容大概是这样:

ID itemName rType CreateDate

1 item1 5 2022 年 1 月 29 日

1 item2 4 2022 年 1 月 29 日

2 item1 5 2022 年 1 月 29 日

1 item2 4 2022 年 1 月 29 日

1 item3 3 2022 年 1 月 29 日

2 item4 3 2022 年 1 月 29 日

3 item5 4 2022 年 1 月 29 日


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK