Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

sql server 2005 - Query examples in a many-to-many relationship

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:

  1. How to get all records in TableA, based on an ID in TableB

  2. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
  • All records in Users based on Addresses.Id
SELECT        Users.*
FROM            Addresses INNER JOIN
                         UserAddresses ON Addresses.Id = UserAddresses.AddressId INNER JOIN
                         Users ON UserAddresses.UserId = Users.Id
WHERE        (Addresses.Id = @AddressId)
  • All records in Addresses based on Users.Id
SELECT        Addresses.*
FROM            Addresses INNER JOIN
                         UserAddresses ON Addresses.Id = UserAddresses.AddressId INNER JOIN
                         Users ON UserAddresses.UserId = Users.Id
WHERE        (Users.Id = @UserId)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...