简体   繁体   中英

MYSQL - SELECT products WHERE parent_category is active

assuming we have a database category structure like this

# Categories Table
| category_id | parent_category_id | status |

# Products Table
| product_id | category_id |

how do i get the list of products in a category only if the parent_category_id has an active status = 1 ?

i guess i could use some sub-query in the SELECT statement, but i don't know how! :(

something like:

SELECT p.*, (SELECT * FROM ? WHERE ? ) AS x 
FROM products AS p 
    LEFT JOIN categories AS c ON p.category_id = c.category_id 
WHERE ... 
AND p.product_id = '?' 
AND ...

Thank you in advance for any advice!

NB: i'm using PHP as backend language, just in case i need some sort of data manipulation to pass to the mysql query.

try not to use subquery, because it can affect the speed of loading data

maybe it can help

SELECT *
FROM categories c
INNER JOIN products p ON p.category_id=c.category_id
WHERE c.status = 1
SELECT p.* FROM products p
INNER JOIN categories child ON child.category_id = p.category_id
INNER JOIN categories parent ON parent.category_id = child.parent_category_id
WHERE parent.status=1

Here a example query, I don't use left join or join, becasue you require that the record exists in order to get the status.

SELECT 
   *
FROM
   products, categories
WHERE
   products.category_id = categories.category_id
   AND status = '1'

First you have to get all active categories

SELECT child.*
FROM Categories child
JOIN Categories parent
  ON child.parent_category_id = parent.category_id 
 AND parent.status = 1

But you also need the root categories with not parent_id

SELECT *
FROM Categories
WHERE parent_category_id IS NULL
  AND status = 1

So you UNION both

SELECT *
FROM Categories child
JOIN Categories parent
  ON child.parent_category_id = parent.category_id 
 AND parent.status = 1

UNION ALL

SELECT *
FROM Categories
WHERE parent_category_id IS NULL
  AND status = 1

Now you get the products for those categories

SELECT *
FROM (  ... UNION ALL ... ) active_categories
JOIN Products
 ON active_categories.category_id = Product.category_id 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM