简体   繁体   English

一对多关系-MySQL

[英]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_id
prod_name prod_name
cat_fid cat_fid

Product Categories 产品类别
cat_id cat_id
cat_name cat_name

Obviously, cat_fid is the foreign key here to the Categories table. 显然,cat_fid是类别表的外键。 Now the problem: 现在的问题是:
The product 'Su'n belong to categories - Hot, Round & Star 产品'Su'n属于类别-热,圆形和星形
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 prod_id prod_name cat_fid
1 Sun ??? 1太阳???
2 Moon ??? 2月???

cat_id cat_name cat_id cat_name
1 Hot 1觉得火辣
2 Cold 2冷
3 Round 3轮
4. Warm 4.温暖
5 Planet 5星球
6 Star ... etc 6星...等


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. 似乎您应该具有一个包含Product_Id和Product_Name的Product表,一个具有Category_Id和Category_Name的Category表,然后一个具有Product_Id和Category_Id字段的Product_Category表。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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