Query examples in a many-to-many relationship

拟墨画扇 提交于 2019-11-30 05:09:27

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)
SELECT *
FROM a
WHERE id IN (SELECT aid FROM ab WHERE bid = 1234)

or

SELECT a.*
FROM a
JOIN ab ON a.id = ab.aid
WHERE ab.aid = 12345

To insert, that depends on your database (eg whether the primary keys are from sequences, auto-generated or generated in some other fashion or simply composite keys). But you just need:

For that data:

INSERT INTO a VALUES (...)

For the relationship:

INSERT INTO ab VALUES (...)

To get all records in table A based on key in B, in english, you want the records in Table A which have a Join record with that TableB key (Assume tableA_B has two Foreign Key cols, (TabAFK and TabBFK)

  Select * from TableA A
  Where pK In (Select Distinct TabAFK From tableA_B
                Where TabBFK = @TableBKeyValue)

Same thing for other direction

  Select * from TableB B
  Where pK In (Select Distinct TabBFK From tableA_B
                Where TabAFK = @TableAKeyValue)

To insert a new record, do a normal insert into TableA and TableB as necessary... Inserts into the join table (tableA_B) are just the two pks from the two main tables

   Insert TableA (pk, [other columns]) Values(@pkValue,  [other data)
   Insert TableB (pk, [other columns]) Values(@pkValue,  [other data)

-- Then insert into Join table for each association that exists...

  Insert tableA_B (TabAFK, TabBFK)  Values(@PkFromA,  @PkFromB)  

1) select tableA.* from tableA join tableA_B on tableA.id = tableA_B.idA where tableA_B.idB = somevalue

2) select tableB.* from tableB left join tableA_B on tableB.id = tableA_B.idB where tableA_B.idA = somevalue

3) insert depends on your database, but insert into a, insert into b, and then insert into a_b; even with constraints on the tables it should work that way.

hint: don't use IN operator for 1/2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!