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 called Activity Action.
How do I retrieve a result set that tells me what action is applicable for each activity using an sql statement? Here's the table structure
Activity Table -ActivityId(PK), ActivityText
Action Table - ActionId(PK), ActionText
ActivityAction -ActivityActionId(PK), ActivityID, ActionID
I want a resultant table in the format
Activity, Applicable Action
(the Activity column should show ActivityText and Applicable Action should show ActionText)
could you please guide me?
Thank you.
It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.
You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.
This formula can be extended to more than 3 tables to N tables, You just need to make sure that the SQL query should have N-1 join statement in order to join N tables. for joining two tables, we require 1 join statement and for joining 3 tables we need 2 join statements.
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
SELECT ActivityText, ActionText FROM Activity JOIN ActivityAction ON Activity.ActivityId = ActivityAction.ActivityId JOIN Action ON ActivityAction.ActionId = Action.ActionId WHERE Activity.ActivityId = 1;
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