简体   繁体   中英

How can I search upto sub level categories using mysql?

I have a database of 30000 products and all products has assigned different categories. There is a separate table for all categories & sub-categories are also stored into same table. The table structure is something like this

Category_mst

category_id_pk, category_name, parent_id

Product_mst

product_id_pk, product_name, category_id_fk (reference to Category_mst->category_id_pk)

Categories are stored upto any number of sub levels. So there can be categories like below

Clothes > Shirts > Kids > Red Color

Products are stored on any level of Category. I want to make a query or a php script that can find out all the Categories that have no Products under it(upto any sub level).

How can I do this ?

Thanks in advance.

You are trying to store hierarchical data in a database.
The naive approach to this is a very poor one, because MySQL does not support recursive queries (unlike Oracle or SQL-server).
Change your database design.

See: The Nested Set Model hierarchical data
Implementing a hierarchical data structure in a database

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