Join two tables based on relationship defined in third table

前端 未结 3 1633
别那么骄傲
别那么骄傲 2020-12-24 01:36

I have two tables Activity and Action. One or more actions can be performed for an activity. And the relationships between Activity and Action is given in a third table call

相关标签:
3条回答
  • 2020-12-24 01:51
    SELECT ActivityText AS Activity, ActionText AS ApplicableAction
      FROM Activity 
      JOIN ActivityAction on Activity.ActivityId = ActivityAction.ActivityID
      JOIN Action on Action.ActionId = ActivityAction.ActionID
    

    You have IDs in Action table and when you join table ActivityAction on ActivityId key then you are able to join activity table

    0 讨论(0)
  • 2020-12-24 01:52
    SELECT ActivityText, ActionText
    FROM Activity
    JOIN ActivityAction ON Activity.ActivityId = ActivityAction.ActivityId
    JOIN Action ON ActivityAction.ActionId = Action.ActionId
    WHERE Activity.ActivityId = 1;
    
    0 讨论(0)
  • 2020-12-24 02:09

    This should do the trick

    SELECT Activity.ActivityText as Activity, Action.ActionText as ApplicableAction
    FROM ActivityAction
        INNER JOIN Activity
            ON ActivityAction.ActivityId = Activity.ActivityId
        INNER JOIN Action 
            ON ActivityAction.ActionId = Action.ActionId
    

    You should read up on JOINS in databases. Here is a good starting point:

    http://en.wikipedia.org/wiki/Join_%28SQL%29

    Basically what we have here is a many to many relationship between Activity and Action which is resolved by two one-to-many relationships using the a join table called ActivityAction.

    To get the required data back, we are joining ActivityAction to each one of the tables using the appropriate PK and FK columns and then choosing the string columns in the SELECT

    0 讨论(0)
提交回复
热议问题