我有2个型号:
表格结构:
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
。有些产品与优惠有关,有些产品没有,但结果总是相同的。
我做错了吗? 这是一个非常简单的查询,但我无法使其正常工作
答案 0 :(得分:1)
更简单的方法可能是使用聚合查询生成最低要约,并将left join
生成product
表:
SELECT p.name, COALESCE(o.default_price, p.price) AS default_price
FROM shop_product p
LEFT JOIN (SELECT product_id, MIN(price) AS default_price
FROM shop_prodcutoffer
WHERE default_offer = 1
GROUP BY product_id) o ON p.id = o.product_id