[英]SQL Conditionally join tables
I have two tables Task and Allocated_Task.我有两个表 Task 和 Allocated_Task。
Allocated_Task has AT.id, Task.id(can be null), AT.allocated_date Allocated_Task 有 AT.id、Task.id(可以为 null)、AT.allocated_date
Task has Task.id, Task.name etc任务有 Task.id、Task.name 等
User can give either Task.id or AT.id as input用户可以提供 Task.id 或 AT.id 作为输入
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预期输出:如果用户提供 task.id 作为输入,它应该在 Allocated_Tasks 中搜索 task.id 并返回 AT.id,Task.Name(如果存在)或 null,Task.Name 如果它在 Allocated_Tasks 中不存在,如果用户给出AT.id 那么它应该给出 At.id, task.name 如果 Allocated_Task 中的 task.id 不为 null 并且 null 如果 Allocated_Task 中的 task.id
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.更新:任务分配给员工(以千为单位),一个员工可以分配 n 个任务(10s ~ 100s),一个任务可以分配给 n 个员工。
If the user is filtering by Task.Id we only need the lastest Allocated_Task.ID (storing Task Allocated time).如果用户按 Task.Id 过滤,我们只需要最新的 Allocated_Task.ID(存储任务分配时间)。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.