您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

MySQL子查询中的未知列

MySQL子查询中的未知列

我不是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

MySQL 2022/1/1 18:50:04 有286人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶