简体   繁体   English

查询多对多关系MySQL

[英]Querying many-to-many relationship MySQL

Ok, I'm going to do my best to explain this situation: 好的,我将尽力解释这种情况:

I have a table, say, Cup. 我有一张桌子,例如,杯子。 And I have another table Liquids. 我还有另一桌液体。 And there is a many-to-many relationship between them. 它们之间存在多对多的关系。

Cup 杯子

  • idcup 闲置
  • material 材料

Liquid 液体

  • idliquid 流动性
  • liquid 液体

Cup_Has_Liquid Cup_Has_Liquid

  • cup_idcup cup_idcup
  • liquid_idliquid liquid_idliquid

Example: A cup can have "Water", "Milk", "Beer", etc. 示例:杯子可以有“水”,“牛奶”,“啤酒”等。

How would I select just the cups that have both "Milk" AND "Water"? 我如何只选择既有“牛奶”又有“水”的杯子?

Thank you 谢谢

Use a joining table. 使用联接表。

That being a table in the middle that is a hybrid between the two. 那是中间的一张桌子,是两者之间的混合体。 It would have a composite primary key, those 2 keys are linked to each of the primary keys on the tables you are trying to join. 它会有一个复合主键,这两个键链接到您要联接的表上的每个主键。

ie

Liquids table contains LiquidID as it's PK. 液体表包含LiquidID作为PK。 Cups table contains CupID as it's PK. Cups表包含CupID作为PK。

In the middle you have a Lines table and it has a composite primary key. 在中间,您有一个Lines表,它有一个复合主键。 The keys in that table are: 该表中的键是:

LiquidID & CupID. LiquidID和CupID。

You would then link Liquid ID from your joining table to your Liquid table and do the same for the other key going to cups. 然后,您可以将连接表中的液体ID链接到液体表,并对要连接到杯子的其他键执行相同的操作。 You can then reference the liquid ID and CupID from the joining table. 然后,您可以从联接表中引用液体ID和CupID。

I hope this clears it up, it is a really confusing topic. 我希望这可以解决,这是一个非常令人困惑的话题。

EDIT: See this link for info. 编辑:请参阅此链接以获取信息。 :) :)

http://www.joinfu.com/2005/12/managing-many-to-many-relationships-in-mysql-part-1/ http://www.joinfu.com/2005/12/managing-many-to-many-relationships-in-mysql-part-1/

Edit 2 编辑2

The joining table could be something like liquid lines and your query would be something like this. 联接表可以是诸如实线之类的东西,而您的查询将是这样的。

Select * FROM liquidLines where CupID = 1 AND LiquidID = 1 OR CupID = 1 AND LiquidID = 2 选择* FROM liquidLines,其中CupID = 1 AND LiquidID = 1 OR CupID = 1 AND LiquidID = 2

Use this Sub-query :- 使用此子查询:

" Select * From Cups Where In ( Select Liquids Where Names = ' Milk ' And ' Water ' ) ; " “从杯子里选择*(选择名称='牛奶'和'水'的液体);”

Names is a column in table " Liquids ". 名称是表“ Liquids”中的一列。

I guess that should do the job :) 我想那应该做的工作:)

have a nice day. 祝你今天愉快。

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

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