-1

Hello guys i have that 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;

This query first checking if item is purchased and show next item! i want to check if user is purchased that product to return only that product that user is not bought it

table structure = Products: http://prntscr.com/k6ogp4 ,Orders: http://prntscr.com/k6ogrz

max_buys colum on products (if it 1 it can buy it once , if its 0 it can be buyed many times)

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Lubomir Stankov
  • 169
  • 1
  • 3
  • 16

1 Answers1

1

In your case I prefer to have a flexible query to manage requirements and also I think that UNION is not required in this case [if your description is complete].

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

You can also manage any other order according to your requirement.