mysql - 在相关表上使用 sum() 时查询时间缓慢

标签 mysql sql

我有两个表(users 和 xp_points)。我需要获得每个用户的 xp 点的总和。但我的查询似乎非常慢(380 毫秒)。我的数据库相当大。我尝试在用户表上创建一个名为 Total_xp_points 的列,然后查询时间仅下降到 4.6 毫秒。

但我不想手动更新每个用户的总 XP 点。有没有办法优化这个查询的速度?

用户表

+----+-------------+-----------------+
| id |  fullname   | total_xp_points |
+----+-------------+-----------------+
|  1 | John Adams  |              22 |
|  2 | Will Smith  |               0 |
|  3 | Bob McGee   |             125 |
|  4 | Andy Briggs |               0 |
|  5 | Linda James |              20 |
+----+-------------+-----------------+

xp_points 表

+----+---------+------------+-----------+
| id | user_id |    date    | xp_points |
+----+---------+------------+-----------+
|  1 |       1 | 2019-01-05 |        17 |
|  2 |       1 | 2019-03-07 |         5 |
|  3 |       3 | 2019-03-07 |         0 |
|  4 |       3 | 2019-01-08 |       125 |
|  5 |       5 | 2019-01-19 |        20 |
+----+---------+------------+-----------+

此查询花费了380.711毫秒(慢得多)

SELECT
    users.id as user_id,
    users.fullname,
    sum(xp_points.xp_points) AS total_xp_points
FROM
    users
INNER JOIN xp_points
    ON users.id = xp_points.user_id
GROUP BY
    user_id,
    users.fullname
HAVING
    SUM(xp_points.xp_points) > 3
LIMIT 100

结果

+---------+-------------+-----------------+
| user_id |  fullname   | total_xp_points |
+---------+-------------+-----------------+
|       1 | John Adams  |              22 |
|       3 | Bob McGee   |             125 |
|       5 | Linda James |              20 |
+---------+-------------+-----------------+

下一个查询仅需要4.641毫秒(快得多,但我必须在用户表上手动维护我不想要的total_xp_points)

SELECT
    users.id as user_id,
    fullname,
    total_xp_points
FROM users
WHERE
    total_xp_points > 3
limit 100

它给出与第一个查询相同的结果(但执行时间更快)

+---------+-------------+-----------------+
| user_id |  fullname   | total_xp_points |
+---------+-------------+-----------------+
|       1 | John Adams  |              22 |
|       3 | Bob McGee   |             125 |
|       5 | Linda James |              20 |
+---------+-------------+-----------------+

最佳答案

您的问题的一部分可能是GROUP BY。您可以尝试选择子查询,如下所示:

SELECT users.id AS user_id,
       users.fullname,
       (SELECT SUM(xp_points) FROM xp_points WHERE xp_points.user_id = users.id) AS total_xp_points
  FROM users
HAVING total_xp_points > 3
 LIMIT 100

关于mysql - 在相关表上使用 sum() 时查询时间缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55762505/

相关文章:

php - 如何获取最多下载记录

c# - MySQL在线数据库

php - 显示MySQL表中具有特定id的多个字段的数据

mysql - SQL - 使用 UNION 的优先级

mysql - 从 MySQL 到 MS SQL,所有列都无效?

javascript - 将重复的 mysql 结果分组到同一结果下

mysql - 如何选择价格高于 'Movie3' 的标题和价格

php - MySQL 清理 mysql_fetch_row

java - Hibernate (MySQL) 上区分大小写的查询

MySQL - 插入信息后更新列