带子查询的Oracle sql查询还是应该规范化?

时间:2010-07-29 20:53:48

标签: sql oracle database-design plsql

我有下面的查询,但我想知道它是否更有效。我需要电话簿表(pb)中4位员工的名字和姓氏,他们的徽章(员工ID)存储在承诺表中

SELECT Originator_ID, 
(SELECT pb.lname FROM pb WHERE pb.badge = Commitment.Originator_ID) AS Originator_Last_Name, 
(SELECT pb.fname FROM pb WHERE pb.badge = Commitment.Originator_ID) AS Originator_First_Name, 
Checker_ID, 
(SELECT pb.lname FROM pb WHERE pb.badge = Commitment.Checker_ID) AS Checker_Last_Name, 
(SELECT pb.fname FROM pb WHERE pb.badge = Commitment.Checker_ID) AS Checker_First_Name, 
Reviewer_ID, 
(SELECT pb.lname FROM pb WHERE pb.badge = Commitment.Reviewer_ID) AS Reviewer_Last_Name, 
(SELECT pb.fname FROM pb WHERE pb.badge = Commitment.Reviewer_ID) AS Reviewer_First_Name, 
Approver_ID, 
(SELECT pb.lname FROM pb WHERE pb.badge = Commitment.Approver_ID) AS Approver_Last_Name, 
(SELECT pb.fname FROM pb WHERE pb.badge = Commitment.Approver_ID) AS Approver_First_Name 
FROM Commitment 
WHERE Commitment.Approver_ID IN (SELECT pb.badge FROM pb WHERE pb.dept = ?) ORDER BY Commitment_ID  

我的查询是否包含太多子查询?

或者我应该将4个员工徽章标准化并分成一个单独的表格吗?如果我要规范化,似乎我的新表存储徽章需要某种角色列,然后我需要第三个角色查找表?然后为了使事情复杂化,我需要使用传入的绑定变量'dept'通过Approver_ID查询Commitments。不知道该走哪条路。

TABLE: commitment_emp
Commitment_ID (PK) (FK) VARCHAR2(10)
badge (PK) VARCHAR2(10)
role (PK) VARCHAR2(20)

1 个答案:

答案 0 :(得分:3)

使用:

   SELECT c.originator_id, 
          orig.lname,
          orig.fname,
          c.checker_id,
          check.lname,
          check.fname,
          c.reviewer_id,
          review.lname,
          review.fname,
          c.approver_id,
          approve.lname,
          approve.fname
     FROM COMMITMENT c
LEFT JOIN PB orig ON orig.badge = c.originator_id
LEFT JOIN PB check ON check.badge = c.checker_id
LEFT JOIN PB review ON review.badge = c.reviewer_id
     JOIN PB approve ON approve.badge = c.approver_id
                    AND approve.dept ?
 ORDER BY c.commitment_id

JOIN和表别名是你的朋友 - 表设计很好。