简体   繁体   中英

One to Many Relationship - MySQL

I see lot of resources addressing my question, but still I couldn't find a definite solution for this, may be because of lack understanding the concept!

The story here:

Have two tables: Products
prod_id
prod_name
cat_fid

Product Categories
cat_id
cat_name

Obviously, cat_fid is the foreign key here to the Categories table. Now the problem:
The product 'Su'n belong to categories - Hot, Round & Star
The product 'Moon' belongs to categories - Cold, Round, Satellite, Planet
The product 'Earth' belongs to categories - Warm, Round, Planet

Now I want to call all the products under Category Round and then Planet or Hot

prod_id prod_name cat_fid
1 Sun ???
2 Moon ???

cat_id cat_name
1 Hot
2 Cold
3 Round
4. Warm
5 Planet
6 Star ... etc


Thanks for any help

If I'm understanding your question correctly, I think you're missing a third table, a Product to Category table.

Seems like you should have a Product table with Product_Id and Product_Name, a Category table with Category_Id and Category_Name, and then a Product_Category table with the Product_Id and Category_Id fields.

select p.product_id, p.product_name, c.category_id, c.category_name 
from product p
    join product_category pc on p.product_id = pc.product_id
    join category c on pc.category_id = c.category_id
where c.category_name = 'Round'

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