【发布时间】:2016-06-01 22:28:41
【问题描述】:
我有 2 个模型:
- 产品 - 产品列表及其价格
- 优惠 - 产品可以有 0...n 个不同的优惠
表格结构:
Table [shop_product]
Fields: 10
[id]: integer NOT NULL
[name]: varchar(300) NOT NULL
[slug]: varchar(150) NOT NULL
[description]: text NOT NULL
[photo]: varchar(100) NOT NULL
[price]: decimal NOT NULL
[category_id]: integer NOT NULL
[upload_date]: datetime NOT NULL
[is_enabled]: bool NOT NULL
[info_template_id]: integer
Table [shop_productoffer]
Fields: 6
[id]: integer NOT NULL
[price]: decimal NOT NULL
[description]: text NOT NULL
[offer_attribute_id]: integer NOT NULL
[product_id]: integer NOT NULL
[default_offer]: bool NOT NULL
Foreign Keys:
[] ([product_id]) REFERENCES [shop_product]([id])
我想构建一个查询,该查询返回产品列表并通过以下逻辑显示“default_price”字段: 如果产品有报价 --> 显示最低的相关报价 否则显示产品的价格字段
这是我得到的(SQlite3 查询):
SELECT
product.price,
CASE offer.price
WHEN EXISTS(SELECT * FROM shop_productoffer
WHERE shop_productoffer.product_id = product.id)
THEN (SELECT MIN(price) FROM shop_productoffer
WHERE shop_productoffer.product_id = product.id AND
shop_productoffer.default_offer = 1)
ELSE product.price
END AS 'default_price'
FROM shop_product as product
LEFT JOIN shop_productoffer AS offer ON product.id = offer.product_id
看起来,Exists 条件永远不会满足 - 查询始终将 default_price' 值返回为 product.price。有些产品与优惠相关联,有些则没有,但结果始终相同。
我做错了吗? 这是一个非常简单的查询,但我无法使其工作
【问题讨论】:
-
能否分享一下表格的结构、一些示例数据以及您想要得到的结果?