使用子查询重构 SQL 更新以影响多行

问题描述 投票:0回答:1

我有一个有效的 SQL 查询,可以计算库存周转率并更新指定的产品记录。我想重构这个查询来计算和更新多个表行的营业额。我的问题是工作查询(如下)在子查询连接子句中包含一个product_id,我不知道如何删除它。

UPDATE products
SET turnover = (
    WITH RECURSIVE
        -- Generate a table of dates from the last year
        daterange AS (
            SELECT CURDATE() AS date, 1 AS n
            UNION ALL
            SELECT date - INTERVAL 1 DAY, n + 1
            FROM daterange
            WHERE n < 365
        ),
        -- Generate a table of historic inventory AS worth
        history AS (
            SELECT daterange.date, IFNULL(SUM(units.price), 0) worth
            FROM daterange
            LEFT JOIN units
                -- Include units that were acquired before the date
                ON DATE(units.acquired_at) < daterange.date
                -- ...and released after the date, or not at all
                AND (DATE(units.released_at) > daterange.date OR units.released_at IS NULL)
                -- ...and units that are not our specified product
                AND units.product_id = 20593
            GROUP BY daterange.date
        ),
        -- Generate a table of inventory sale totals from the last year
        sales AS (
            SELECT product_id, SUM(price) AS year_total
            FROM units
            WHERE released_at > DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
            GROUP BY product_id
        )
    -- Calculate turnover as annual sales divided by average inventory
    SELECT (sales.year_total) / AVG(history.worth) turnover
    FROM history
    LEFT JOIN sales ON sales.product_id = products.id
)
WHERE id = 20593;

我希望能够删除外部查询上的 where 子句,或者将其替换为

WHERE products.type_id = 5
之类的内容以处理多行。但是,如果不从历史子查询中删除
units.product_id = 20593
,则无法完成此操作,并且替换
units.product_id = products.id
会引发错误“on 子句中的未知列 products.id。”

为了清楚起见,这里使用了两个表格:产品和单位。至少,它们有以下列:

产品单位idid类型_id产品_id营业额价格获得于发布于
任何建议表示赞赏!我愿意探索解决这个问题的不同方法。我正在使用 MariaDB (v15.1)。

sql mariadb
1个回答
0
投票
在 MariaDB 中

有一种更简单(而且可能更快)的方法来生成连续日期表: SELECT '2023-01-01' + INTERVAL seq-1 DAY AS a_date FROM seq_1_to_365

然后扔掉 
WITH

并得到类似的东西

UPDATE ( the above query ) AS dates
    LEFT JOIN products AS p  ON p.date = dates.a_date
    SET p...

© www.soinside.com 2019 - 2024. All rights reserved.