这是我的查询:

SET @date = '2019-02-12';

SELECT lds.product_id, sum(lds.amount) amount, lpp.price
FROM `log_daily_stock` lds
 JOIN (SELECT * FROM log_product_prices
       WHERE created_at <= @date
         AND product_id = lds.product_id          -- the problem is here
       ORDER BY created_at DESC) lpp
 ON lpp.product_id = lds.product_id
WHERE branch_id in (1,2)
  AND stock_date = @date
GROUP BY product_id, price


正如我在查询中评论的那样,lds.product_id不被称为列并抛出:


  #1054-“ where子句”中的未知列“ lds.product_id”


知道如何解决吗?



我想要做的就是获得该产品的最新价格。这就是为什么我将created_at依次订购为DESCLIMIT 1的原因。

最佳答案

你可以尝试如下

SELECT lds.product_id, sum(lds.amount) amount, lpp.price
FROM `log_daily_stock` lds
 JOIN (SELECT * FROM log_product_prices
       WHERE created_at <= @date
       ) lpp
 ON lpp.product_id = lds.product_id
WHERE branch_id in (1,2)
  AND stock_date = @date
GROUP BY lds.product_id, lpp.price

关于mysql - 如何在子查询中使用外部表的名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54668790/

10-11 01:39