我的表格如下:
tbl_tasks
+---------+-------------+
| Task_ID | Assigned_ID |
+---------+-------------+
| 1 | 8 |
| 2 | 12 |
| 3 | 31 |
+---------+-------------+
tbl_resources
+---------+-----------+
| Task_ID | Source_ID |
+---------+-----------+
| 1 | 4 |
| 1 | 10 |
| 2 | 42 |
| 4 | 8 |
+---------+-----------+
将任务分配给至少一个人(由“assigned_ID”表示),然后可以将任意数量的人分配为源(由“source_ID”表示)。 ID号都链接到另一个表中的名称。虽然ID号的名称不同,但它们都返回到同一个表中。
我是否有办法根据ID合并两张表格,以便我可以根据某人的身份证号码进行搜索?例如 - 如果我决定搜索或执行WHERE User_ID = 8,为了查看涉及8的任务,我将返回任务1和任务4。
现在,通过将所有表连接在一起,由于表中的所有多个条目,我可以轻松过滤“已分配”但不过滤“源”。
答案 0 :(得分:1)
使用union all
:
select distinct task_id
from ((select task_id, assigned_id as id
from tbl_tasks
) union all
(select task_id, source_id
from tbl_resources
)
) ti
where id = ?;
请注意,如果有人在两个表中分配了相同的任务,则会使用select distinct
。如果没有,请删除distinct
。