not needed anymore
not needed anymore

Reputation: 33

How to select dependent columns from a single table in MySQL

I have products_table like this:

prod_ID (int), sub_of (int), category (int), price (decimal 10,2), sort (int)

Main products has sub_of set to 0, category set to some id from other table and no price set. only sub products has price, but no category.

My english is bad, so I'll try to ask the question with SQL:

I want to

SELECT * 
  FROM products_table 
    WHERE category IN (3, 158, 159, 160, 249) 
      AND sub_of = 0
      AND price >= 27 
      AND price <= 34 
  ORDER BY sort+0, sort

How can I do this?

I'm tring with SELECT in SELECT but does not select correct prices:

$where = ajax: AND price >= 27 AND price <= 34
$daOrder = SORT BY sort+0, sort

$query = "SELECT * 
FROM ".PRODUCTS_TABLE." 
WHERE prod_ID IN (
    SELECT sub_of
    FROM ".PRODUCTS_TABLE." 
    WHERE sub_of IN (
        SELECT prod_ID
        FROM ".PRODUCTS_TABLE." 
        WHERE category IN (".$allCats.") 
    ) 
    ".mysql_escape_string($where)." {$daOrder}
)";

Edit:

I need all main products (sub_of=0) from some categories and with price range, then I will list all sub products of each main product.

Upvotes: 2

Views: 406

Answers (2)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 658202

Your question still leaves room for interpretation.

This gives you all main-products of the the chosen categories where all sub-products are within the given price range (none cheaper or more expensive):

SELECT m.*
FROM   products_table m
JOIN  (
    SELECT sub_of AS prod_id
    FROM   products_table p
    WHERE  p.category IN (3, 158, 159, 160, 249)
    GROUP  BY 1, p.category    -- only useful if there are multiple cat. per main-prod
    HAVING min(price) >= 27
    AND    max(price) <= 34
    ) p USING (prod_id)
WHERE  m.sub_of = 0            -- should be redundant if your data model is clean
ORDER  BY m.sort + 0, m.sort;  -- copied the weird ORDER BY verbatim

Accordingly, this returns all sub-products belonging to the main-products above:

SELECT s.*
FROM   products_table s
JOIN  (
    SELECT sub_of
    FROM   products_table p
    WHERE  p.category IN (3, 158, 159, 160, 249)
    GROUP  BY 1, p.category
    HAVING min(price) >= 27
    AND    max(price) <= 34
    ) p USING (sub_of)
WHERE  s.sub_of <> 0           -- should be redundant if your data model is clean
ORDER  BY s.sort + 0, s.sort;  -- copied the weird ORDER BY verbatim

Upvotes: 0

Florian Grell
Florian Grell

Reputation: 1025

I would go for a self-join:

SELECT *
FROM products_table as main_products
LEFT JOIN products_table as sub_products
   ON sub_products.sub_of = main_products.prod_id
WHERE main_products.category IN (3, 158, 159, 160, 249)
  AND sub_products.price >= 27
  AND sub_products.price <= 34
ORDER BY sub_products.sort

Upvotes: 1

Related Questions