MySql - Sub-query/Outer 子 table (1:n) 中列的 SUM() 使用 LIMIT 连接

MySql - SUM() of column in child table (1:n) in a Sub-query/Outer Join using LIMIT

我有两个表 - PRODUCT,ACTIVITY。每个产品可以有多个 activity (1:n)。每个 activity 都有一个 (INT) 操作列。我需要查询 10 个最近 活动的所有产品和 SUM(product.action)。

我的第一次尝试是使用子查询:

select p.*, (select sum(a.action) from activity a 
        where a.product_id = p.product_id
        order by a.timestamp desc limit 10) recent
from product p

然而,结果不正确。我意识到子查询没有使用 LIMIT,而是返回与 product_id 匹配的所有 ACTIVITY 记录的 SUM()。

我的第二次尝试是遵循建议 here 并将子查询包装在另一个 select 查询中:

select p.*, (select sum(temp.action) as recent
from (select a.action from activity a 
        where a.product_id = p.product_id 
        order by a.timestamp desc limit 10) temp)
from product p

但是,我收到了错误消息 错误代码:1054。'where clause' 中的未知列 'p.product_id'。我发现了一个相关问题 here 并意识到 MYSQL 不支持二级嵌套的别名。我不太理解那个问题的答案。

我也试过外连接

select p.*, sum(temp.action) as recent
from product p
left join
(select a.product_id, a.action from activity a 
        where a.product_id = p.product_id
        order by a.timestamp desc limit 10) temp
on p.product_id= temp.product_id

同样,我 运行 遇到了同样的问题:

  1. LIMIT 未强制执行
  2. 无法识别别名

我该如何解决这个问题?

1- 从您的产品中获取不同的产品 table
2- 获取每个产品的十个最近活动
3- 从 (2)
中获取总和 4- 加入

看看Using LIMIT within GROUP BY to get N results per group?。这听起来与您需要的 (2) 相似。

编辑

我稍微修改了查询并在一个小数据集上对其进行了测试。以前的版本不工作,因为 where 子句在错误的地方。见下文。

select t.product_id, sum(t.action) from
(
    select product_id, action, timestamp, 
    @row_num := if(@prev = product_id, @row_num + 1, 1) as row_num, @prev := product_id 
    from activity
    join (select @prev := null, @row_num := 0) as vars
    order by product_id, timestamp desc
) as t
where t.row_num <= 10
group by t.product_id;