一尘不染

MySQL子查询中的未知列

sql

我试图获取一个项目的平均值,所以我正在使用子查询。

更新 :我本来应该更清楚一些,但我希望平均水平仅适用于最后5个项目

首先我开始

SELECT 
y.id
FROM (
    SELECT *
        FROM (
                SELECT *
                FROM products
                WHERE itemid=1
        ) x  
    ORDER BY id DESC
    LIMIT 15 
) y;

它可以运行,但是因为它仅向我显示了ID,所以它毫无用处。

然后我在下面添加

SELECT
y.id,
(SELECT AVG(deposit) FROM (SELECT deposit FROM products WHERE id < y.id ORDER BY id DESC LIMIT 5)z) AVGDEPOSIT
FROM (
    SELECT *
        FROM (
                SELECT *
                FROM products
                WHERE itemid=1
        ) x  
    ORDER BY id DESC
    LIMIT 15 
) y;

当我这样做时, 在“ where子句”中 收到错误 Unknown列“ y.id”
,在这里进一步阅读时,我相信这是因为当查询下降到下一个级别时,它们需要联接吗?

所以我尝试了以下**删除了不需要的suquery

SELECT
y.id,
(SELECT AVG(deposit) FROM (
    SELECT deposit 
    FROM products
    INNER JOIN y as yy ON products.id = yy.id       
    WHERE id < yy.id 
    ORDER BY id DESC 
    LIMIT 5)z
    ) AVGDEPOSIT
FROM (
    SELECT *
    FROM products
    WHERE itemid=1
    ORDER BY id DESC
    LIMIT 15 
) y;

但是我得到 表’test.y’不存在 。我在正确的轨道上吗?我需要改变什么才能得到我想要的东西?

该示例可以在sqlfiddle中找到。

CREATE TABLE products
    (`id` int, `itemid` int, `deposit` int);

    INSERT INTO products
    (`id`, `itemid`, `deposit`)
VALUES
(1, 1, 50),
(2, 1, 75),
(3, 1, 90),
(4, 1, 80),
(5, 1, 100),
(6, 1, 75),
(7, 1, 75),
(8, 1, 90),
(9, 1, 90),
(10, 1, 100);

给定我在此示例中的数据,我的预期结果在下面,每个ID旁边都有一列,该列具有前5次存款的平均值。

id | AVGDEPOSIT
10 | 86 (deposit value of (id9+id8+id7+id6+id5)/5) to get the AVG
 9 | 84
 8 | 84
 7 | 84
 6 | 79
 5 | 73.75

阅读 236

收藏
2021-05-16

共1个答案

一尘不染

我不是MySQL专家(在MS SQL中可以更轻松地完成操作),您的问题对我来说似乎有点不清楚,但似乎您正在尝试获取前5个项目的平均值。

如果您的 ID没有空格 ,这很容易:

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

[sql fiddle demo](http://sqlfiddle.com/#!2/56fadb/4)

2021-05-16