我不是MysqL专家(在MS sql中可以更轻松地完成操作),您的问题对我来说似乎有点不清楚,但似乎您正在尝试获取前5个项目的平均值。
如果您的 ,这很容易:
select
p.id,
(
select avg(t.deposit)
from products as t
where t.itemid = 1 and t.id >= p.id - 5 and t.id < p.id
) as avgdeposit
from products as p
where p.itemid = 1
order by p.id desc
limit 15
,那么我已经尝试过这样的查询
select
p.id,
(
select avg(t.deposit)
from (
select tt.deposit
from products as tt
where tt.itemid = 1 and tt.id < p.id
order by tt.id desc
limit 5
) as t
) as avgdeposit
from products as p
where p.itemid = 1
order by p.id desc
limit 15
但是我有例外UnkNown column 'p.id' in 'where clause'
。看起来MysqL无法处理2级嵌套的子查询。但是您可以使用来获得5个先前的项目offset
,例如:
select
p.id,
(
select avg(t.deposit)
from products as t
where t.itemid = 1 and t.id > coalesce(p.prev_id, -1) and t.id < p.id
) as avgdeposit
from
(
select
p.id,
(
select tt.id
from products as tt
where tt.itemid = 1 and tt.id <= p.id
order by tt.id desc
limit 1 offset 6
) as prev_id
from products as p
where p.itemid = 1
order by p.id desc
limit 15
) as p