Search code examples
mysqldatabasemany-to-many

How to do MySQL CRUD select on a many to many relationship


I am trying to perform a Create, Select, Update and Delete operation on a many to many relationship with an intermediary table (associative table). I have the following structure. Assume FK constraints in the intermediary table where the names match.

tbl_A and tbl_B have a many to many relationship. tbl_IM is the intermediary table.

tbl_A
aID 
Name

tbl_B
bID
Name
UniqueField

Intermediary Table tbl_IM
imID
aID
UniqueField

a tbl_A item can have many tbl_B items, and a tbl_B item can belong to many tbl_A items.

tbl_B is generally a fixed set of 18 records or so (for allowable selections in a program).

How do I Select and Update all tbl_B items that belong to a particular tbl_A item? How do I get the whole set of tbl_A items along with their associated tbl_B items?

Please do not use wild cards (Select *). My example has only 2 fields each for brevity; I need to see how it is done by using fields. Casting is acceptable--so P1.aID is fine.

I have looked at question Select in a many-to-many relationship in MySQL but it is not clear to me how it applies to my situation.


Solution

  • Create A view that will display the fields you want

    CREATE VIEW combined AS SELECT tbl_A.name, tbl_B.bName
    FROM tbl_B INNER JOIN (tbl_A INNER JOIN tbl_M ON tbl_A.ID = tbl_M.AId) ON tbl_B.unique = tbl_M.Unique;
    

    Then you can perform CRUD operation on the view as if it was a table