简体   繁体   中英

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_idcup
  • 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. Cups table contains CupID as it's PK.

In the middle you have a Lines table and it has a composite primary key. The keys in that table are:

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. You can then reference the liquid ID and CupID from the joining table.

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/

Edit 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

Use this Sub-query :-

" Select * From Cups Where In ( Select Liquids Where Names = ' Milk ' And ' Water ' ) ; "

Names is a column in table " Liquids ".

I guess that should do the job :)

have a nice day.

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