Jeg er ikke en MySQL-ekspert (i MS SQL kunne det gøres lettere), og dit spørgsmål ser lidt uklart ud for mig, men det ser ud til, at du forsøger at få et gennemsnit af de foregående 5 elementer.
Hvis du har Id uden huller , det er nemt:
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
Hvis ikke , så har jeg prøvet at lave denne forespørgsel på denne måde
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
Men jeg har en undtagelse Unknown column 'p.id' in 'where clause'
. Det ser ud til, at MySQL ikke kan håndtere 2 niveauer af indlejring af underforespørgsler. Men du kan få 5 tidligere elementer med offset
, sådan her:
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