这是我的查询
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
依次订购为DESC
和LIMIT 1
的原因。
答案 0 :(得分:0)
您可以尝试以下操作
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
答案 1 :(得分:0)
一种方法是相关子查询:
SELECT lds.product_id, sum(lds.amount) as amount,
(SELECT lpp.price
FROM log_product_prices lpp
WHERE lpp.created_at <= @date AND
lpp.product_id = lds.product_id
ORDER BY created_at DESC
) as price_asof_date
FROM `log_daily_stock` lds
WHERE branch_id in (1, 2) AND stock_date = @date
GROUP BY product_id, price