如何在使用多个连接时保留密钥?

9rbhqvlz  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(273)

在下面的代码中,我创建了一个用于显示人员相关数据的视图表。对于每个员工,我需要从staff中获取所有列,以及从department表中获取dept\u title,从unit表中获取unit\u title。基本上,我将“单位”表与“单位\职员”表(单位\职员是单位与职员之间的连接表)的内部连接结果与“单位”表的连接结果一起留在了“职员”表中。所以现在我在同一个视图中有三个不同表的所有不同列。
(职员------左入------>(单位------内入------>单位职员)--左入------>部门

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;
/

问题是视图中没有保留密钥。以前,我没有在视图中包含“department”表,并且在插入数据时保留密钥也没有问题。所以我认为添加具有一对一关系的“department”表不会破坏密钥保存,但它确实做到了。我认为问题在于我对不同列进行分组的方式。如何更改上述代码以保留密钥?

pkwftd7m

pkwftd7m1#

我认为移除聚合并使用子查询将解决问题:

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;

相关问题