简体   繁体   中英

SQL Conditionally join tables

I have two tables Task and Allocated_Task.

Allocated_Task has AT.id, Task.id(can be null), AT.allocated_date

Task has Task.id, Task.name etc

User can give either Task.id or AT.id as input

select AT.id, Task.Name 
from Allocated_Task, Task 
where (Task.id = :INPUT_TASK_ID or AT.id = :INPUT_AT_id)

Expected Output: If user gives task.id as input it should search for task.id in Allocated_Tasks and return AT.id, Task.Name if it exists or null, Task.Name if it doesn't exist in Allocated_Tasks, If user gives AT.id then it should give At.id, task.name if task.id in Allocated_Task is not null and null if task.id in Allocated_Task

Allocated Task

AT.id | Task.id
---------------
  1   |  10
  2   |  null

Task

Task.Id | Name
----------------
     10 | Name1
     20 | Name2

OUTPUT:

AT.ID | NAME
---------------------------------------------------
1     | Name1 (if user gives 1 as INPUT_AT_id)
2     | null (if user gives 2 as INPUT_AT_id)
1     | Name1 (if user gives 10 as INPUT_TASK_ID)
null  | Name2 (if user gives 20 as INPUT_TASK_ID)

Update: Tasks are assigned to employees(in Thousands) and an employee can be assigned n number of tasks(10s ~ 100s) and a task can be allocated to n number of employees.

If the user is filtering by Task.Id we only need the lastest Allocated_Task.ID (storing Task Allocated time). Using full outer join is taking a few minutes to execute which is not ideal in this case. Is it possible to improve query efficiency?

It is FULL JOIN:

SELECT AT.id, T.Name
FROM Allocated_Task AT
FULL JOIN Task T
  ON AT.TaskId = T.Id
WHERE T.id = :INPUT_TASK_ID
  OR AT.id = :INPUT_AT_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM