如何保留使用多个连接的密钥?
Posted
技术标签:
【中文标题】如何保留使用多个连接的密钥?【英文标题】:How to preserve key where multiple joins are used? 【发布时间】:2020-06-04 08:45:51 【问题描述】:在下面的代码中,我创建了一个用于显示员工相关数据的视图表。对于每个员工,我需要从员工那里获取所有列,以及从“部门”表中获取“dept_title”,从“单元”表中获取“unit_title”。基本上我有 LEFT JOINED "staff" 表,其结果来自 INNER JOINING "unit" table with "unit_staff" staff table("unit_staff" 是 unit 和 staff 之间的连接表)。加入这三个表的结果是 LEFT JOINED with “部门”表。所以现在我在同一个视图中拥有来自三个不同表的所有不同列。
( staff-----left join-----> ( unit-----Inner加入----->unit_staff ) ) -----左加入----->部门
CREATE OR REPLACE FORCE VIEW "V_STAFF" (
"STAFF_ID",
"STAFF_NAME",
"SALUTATION",
"GENDER",
"CONTACT_NO",
"PRIMARY_EMAIL",
"SECONDARY_EMAIL",
"DOB", "ADDRESS",
"NATIONALITY",
"STAFF_TYPE",
"DEPT_NAME",
"UNITS_NAME"
) AS
SELECT staff.staff_id,
staff.staff_name,
staff.salutation,
staff.gender,
staff.contact_no,
staff.primary_email,
staff.secondary_email,
staff.dob,
staff.address,
staff.nationality,
staff.staff_type,
department.dept_title,
LISTAGG(unit_title, ',') WITHIN GROUP (ORDER BY unit_title) AS units
FROM (staff
LEFT JOIN (unit_staff INNER JOIN unit ON unit_staff.unit_id = unit.unit_id)
ON staff.staff_id = unit_staff.staff_id) LEFT JOIN department ON staff.dept_id = department.dept_id
GROUP BY staff.staff_id,
staff.staff_name,
staff.salutation,
staff.gender,
staff.contact_no,
staff.primary_email,
staff.secondary_email,
staff.dob,
staff.address,
staff.nationality,
staff.staff_type,
department.dept_title;
/
问题在于视图中没有保留密钥。以前,我没有在视图中包含“部门”表,并且在插入数据时保存密钥没有问题。所以我认为添加具有一对一关系的“部门”表不会破坏密钥保存,但确实如此。我认为问题在于我对不同列进行分组的方式。如何更改上述代码以保留密钥?
【问题讨论】:
这里最重要的部分是对表的约束。 Oracle 通过确保您的尝试匹配相关的 PK/FK 约束来确定是否保留密钥。 【参考方案1】:我认为删除聚合并使用子查询将解决问题:
select s.*,
(select listagg(u.unit_title, ',') WITHIN GROUP (ORDER BY unit_title) AS units
from unit_staff us join
unit u
on us.unit_id = u.unit_id
where s.staff_id = us.staff_id)
) as units,
(select d.dept_title
from department d
where s.dept_id = d.dept_id
) as dept_tital
from staff s;
【讨论】:
以上是关于如何保留使用多个连接的密钥?的主要内容,如果未能解决你的问题,请参考以下文章