<分区>
尝试通过首先将它们的 time_spent 求和来检索记录,然后使用 max 按时间检索最大的记录。这似乎有效。
我现在需要检查用户的 time_spent 总和是否有相同的值(平局,如下例所示,两个用户的 time_spent 都为 10,因此它应该选择具有最新的用户发布),如果是,那么我只需要使用 created_at 列获取最后(更新)发布的 user_id。我只是不知道用什么来做那个检查,是 CASE 还是 IF 函数?如果是这样,它会在我的查询中去哪里?
这是一个 sql fiddle 链接:http://sqlfiddle.com/#!9/f24985/2
表1布局
+----+---------+-----------+---------+------------+------------+
| id | user_id | member_id | item_id | time_spent | created_at |
+----+---------+-----------+---------+------------+------------+
| 1 | 1 | 1 | 1 | 5 | 2019-06-01 |
| 2 | 2 | 1 | 1 | 1 | 2019-06-07 |
| 3 | 2 | 1 | 1 | 5 | 2019-06-08 |
| 4 | 2 | 1 | 2 | 4 | 2019-06-01 |
| 5 | 1 | 1 | 2 | 5 | 2019-06-07 |
+----+---------+-----------+---------+------------+------------+
当前 SQL:
SELECT
MAX(attribute_time.sum_time), attribute_time.user_id
FROM (
SELECT
SUM(time_spent) AS sum_time, user_id
FROM
table1
WHERE
member_id = 1
AND item_id IN (1, 2)
AND (created_at BETWEEN '2019-06-1' AND '2019-06-30')
GROUP BY
user_id
ORDER BY
sum_time desc
) AS attribute_time;
在这个例子中,两个用户总共有 10 个时间,当前返回 2 的第一条记录,而不是基于 created_at 日期,在这种情况下,应该是用户 2。
预期
+---------+
| user_id |
+---------+
| 2 |
+---------+