table relationship
Hi all I need help with how to enter and pull data from a simple many-to-many relationship table in MYSQL as I’m totally lost and about to go with a SET datatype but I know many-to-many is the correct way to do this. I’ve included a picture of the table layout to help you better understand. I have 3 tables (shirt, shirt2color, color). The shirt table has 2 columns (shirt_id, shirt), the shirt2color (mapping table) has 2 columns (shirt_id, color_id), and the color table has 2 columns (color_id, color).
I have already created the tables and relationships but how do I enter and pull data without manually mapping? Isn’t there an INSERT statement where I could add the t-shirt and tell the database it’s available colors in one statement and it would add “t-shirt” and “red, green, and blue” to the database as well as populate the mapping table automatically? Using the examples in the photo as a guide: (p.s. I imagine that’s how the example relationship data gets stored in the mapping table, if not please let me know)
- What would the SQL statement be to INSERT the t-shirt (which is available in red, green, and blue)?
- What would the SQL statement be to SELECT and list all shirts that are available in Red?
- How do you handle duplicate colors on shirt entries? For example if I add another shirt that comes in red I don’t want to add the color red again with color_id #4, I’d want to use color_id #1.
I know these are probably total newbie questions but I can’t find the answer to these questions anywhere online over the last few weeks. Thanks for any help you guys can offer.