大家好,我有那个SQL:
SELECT p.* FROM products p WHERE required_product_id IS NULL
UNION ALL
SELECT p.* FROM products p, orders o WHERE p.required_product_id = o.product_id
AND o.user_id = 1
UNION DISTINCT
SELECT p.`*` FROM products p, orders o WHERE p.id NOT IN (SELECT product_id FROM orders WHERE product_id = p.id AND o.user_id = 1)
AND p.max_buys = 1;
此查询首先检查是否购买了商品并显示下一个商品!我想检查用户是否购买了该产品,以仅退还该用户未购买的产品
表结构=产品:http://prntscr.com/k6ogp4,订单:http://prntscr.com/k6ogrz
max_buys列于产品上(如果为1,则可以购买一次;如果为0,则可以多次购买)
答案 0 :(得分:1)
在您的情况下,我希望有一个灵活的查询来管理需求,并且我认为在这种情况下[如果您的描述完整]则不需要UNION。
SELECT w.* from (
SELECT
(SELECT count(o.product_id) FROM orders o WHERE o.product_id = p.id AND o.user_id = 1) bought_count,
(SELECT count(q.product_id) FROM orders q WHERE q.product_id = p.required_product_id AND q.user_id = 1) order_depend,
p.*
FROM products p ) w
where
(order_depend>0 or required_product_id is null) and -- unlock order depended products
(max_buys=0 or -- can buy more than once
bought_count=0) -- or not bought yet
order by
order_depend desc, -- dependent products to ordered products in first level
bought_count asc, -- not bought products in second level
recommended desc -- recommended products in third level
您还可以根据需要管理其他任何订单。