union mysql,检查其粗体

z9ju0rcb  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(375)

大家好,我有一个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\ U在产品上购买colum(如果它是1,它可以购买一次,如果它是0,它可以购买多次)

0dxa2lsx

0dxa2lsx1#

在您的情况下,我更希望有一个灵活的查询来管理需求,而且我认为在这种情况下不需要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

您也可以根据您的要求管理任何其他订单。

相关问题