UNION MySQL, 检查是否为粗体

UNION MySQL, Check if its bold

大家好,我有 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;

此查询首先检查商品是否已购买并显示下一个商品!我想检查用户是否购买了该产品 return 只有用户未购买的产品

table结构=产品:http://prntscr.com/k6ogp4 ,Orders: http://prntscr.com/k6ogrz

max_buys产品栏目(1可以购买一次,0可以购买多次)

在你的情况下,我更喜欢使用灵活的查询来管理需求,而且我认为在这种情况下不需要 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

您还可以根据需要管理任何其他订单。