Wow, it's hard to find a simple explanation to this topic. A simple many-to-many relationship.
Three tables, tableA, tableB and a junction tableA_B.
I know how to set up the relationship, with keys and all, but I get a little confused when time comes to perform INSERT, UPDATE and DELETE queries....
Basically, what I am looking for is an example that shows:
How to get all records in TableA, based on an ID in TableB
How to get all records in TableB, based on an ID in TableA
3 How to INSERT in either TableA or TableB, and then make the appropriate INSERT in the junction table to make the connection..
I'm not looking for a solution to a specific project, just a few general examples that can be applied. Maybe you have something lying around?
A many-to-many relationship between two tables can be established by creating a table typically called as bridge/junction/join table and adding foreign-key constraints from it to the original tables. These two tables are related via a many-to-many relationship. i.e: an article can have many tags.
A many-to-many relationship exists when one or more items in one table can have a relationship to one or more items in another table. For example: Your Order table contains orders placed by multiple customers (who are listed in the Customers table), and a customer may place more than one order.
When you have a many-to-many relationship between dimension-type tables, we provide the following guidance: Add each many-to-many related entity as a model table, ensuring it has a unique identifier (ID) column. Add a bridging table to store associated entities. Create one-to-many relationships between the three tables.
Relational databases don't support direct many-to-many relationships between two tables. Then, how to implement many-to-many relationships in SQL? To create a many-to-many relationship in a database, you'll need to create a third table to connect the other two.
The first thing I would do is recommend using an ORM like Linq-To-Sql or NHibernate which will give you object representations of your data-model which make it much simpler to handle complex things like many-to-many CRUD operations.
If an ORM isn't part of your tool set then here is how this would look in SOL.
Users UserAddresses Addresses ======= ============= ========= Id Id Id FirstName UserId City LastName AddressId State Zip
Our tables are joined like this:
Users.Id -> UserAddresses.UserId Addresses.Id -> UserAddresses.AddressId
SELECT Users.* FROM Addresses INNER JOIN UserAddresses ON Addresses.Id = UserAddresses.AddressId INNER JOIN Users ON UserAddresses.UserId = Users.Id WHERE (Addresses.Id = @AddressId)
SELECT Addresses.* FROM Addresses INNER JOIN UserAddresses ON Addresses.Id = UserAddresses.AddressId INNER JOIN Users ON UserAddresses.UserId = Users.Id WHERE (Users.Id = @UserId)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With