【发布时间】:2011-01-25 11:02:33
【问题描述】:
我有两张桌子:
product (idproduct, name, description, tax)
product_storage (idstorage, idproduct, added, quantity, price)
对于每种产品,它可能有不同的价格,最早的产品是“最先销售”
例如在我的存储中:
1, 1, 2010-01-01, 0, 10.0
2, 1, 2010-01-02, 0, 11.0
3, 1, 2010-01-03, 10, 12.0
4, 2, 2010-01-04, 0, 12.0
5, 2, 2010-01-05, 10, 11.0
6, 2, 2010-01-06, 10, 13.0
7, 3, 2010-01-07, 10, 14.0
8, 3, 2010-01-08, 10, 16.0
9, 3, 2010-01-09, 10, 13.0
现在我需要选择当前价格的所有产品,它位于 product_storage 中最旧的行中,其中每个产品的数量 > 0:
SELECT p.idproduct, p.name, p.tax,
(SELECT s.price
FROM product_storage s
WHERE s.idproduct=p.idproduct AND s.quantity > 0
ORDER BY s.added ASC
LIMIT 1) AS price
FROM product p;
工作正常,但当我想在查询中计算含税价格时却不行:
SELECT p.idproduct, p.name, p.tax,
(SELECT s.price
FROM product_storage s
WHERE s.idproduct=p.idproduct AND s.quantity > 0
ORDER BY s.added ASC
LIMIT 1) AS price,
(price * (1 + tax/100)) AS price_with_tax
FROM product p;
MySQL 说:
Unknown column 'price' in 'field list'
更新
使用子查询作为表几乎可以解决问题(查看答案)——现在唯一的问题是如何从 product_storage 中为多个外键选择最旧的行(每个 idproduct 一个且只有一个)。
更新 2
感谢 cmptrgeekken 提供了很好的解决方案 :))
【问题讨论】: