I have the following setup: Tasks, Accounts and Groups tables. Tasks can be assigned to both individual accounts and groups. I've made two supporting tables: TasksAndAccounts and AccountsInGroups. TasksAndAccounts table has the following fields: TaskId, AccountId, GroupId and AccountsInGroups has AccountId and GroupId fields. I'm trying to write a query that will return all tasks assigned to a given account id. The culprit here is the query should look first in TasksAndAccounts table to see if there are tasks related directly to the given account and then also look for any groups that the given account is associated with.
The basic algorithm is simple:
- Get all tasks from TasksAndAccounts where TasksAndAccounts.AccountId == accountId
- Get all groups from AccountsInGroups where AccountsInGroups.AccountId == accountId
- Get all tasks from TasksAndAccounts where TasksAndAccounts.GroupId is in the result set from step 2.
- Merge steps 1 and 3.
I've tried to tackle the issue in a few different ways but wasn't able to get any satisfactory result.
Any ideas on writing an elegant single query solution?