You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用单条MySQL查询对比用户各稀有度物品拥有量与总量

单条SQL实现用户稀有度物品持有量与全量统计合并查询

可以通过子查询关联或窗口函数两种方式,将用户持有量统计与稀有度全量统计合并为单条查询,避免多次查询拼接的效率损耗:

方法1:子查询关联

先通过子查询预计算各稀有度的总物品数,再与用户持有统计的结果关联,一次查询输出所需数据:

SELECT 
    u.user_owned,
    c.rarity,
    COUNT(c.rarity) AS user_rarity_count,
    r.total_rarity_count
FROM tb_items c
INNER JOIN tb_inventories u ON u.item_name = c.item_name
INNER JOIN (
    SELECT rarity, COUNT(*) AS total_rarity_count
    FROM tb_items
    GROUP BY rarity
) r ON c.rarity = r.rarity
GROUP BY u.user_owned, c.rarity, r.total_rarity_count;

方法2:窗口函数(更简洁)

利用MySQL的窗口函数,在统计用户持有量的同时直接计算对应稀有度的全量总数,无需额外子查询关联:

SELECT 
    u.user_owned,
    c.rarity,
    COUNT(c.rarity) AS user_rarity_count,
    COUNT(*) OVER (PARTITION BY c.rarity) AS total_rarity_count
FROM tb_items c
INNER JOIN tb_inventories u ON u.item_name = c.item_name
GROUP BY u.user_owned, c.rarity;

性能优化提示

为提升大数据量下的查询效率,建议创建以下索引:

  • tb_items:INDEX idx_item_rarity (item_name, rarity)
  • tb_inventories:INDEX idx_user_item (user_owned, item_name)

内容的提问来源于stack exchange,提问作者Zoey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 09:10:24