为什么我会收到大量重复记录?

时间:2019-11-15 06:12:41

标签: sql oracle

从下面的查询中,我获得了118条记录。我想从Emp_master表中获取用户名。我想将D.prepared_by与Emp_Master表的两列(Emp_Initial和Emp_no)进行比较,并想从Employee表中获取Emp_Name。

SELECT D.Prepared_By, D.location, C.INSTRUMENT_NO, D.EQP_SRL_NO, D.INSTRUMENT_NAME, B.PLAN, A.DETAIL, C.MAINTENANCE_FREQ, C.PERIOD, 
    C.MAINTAIN_ON_DUEDATE,C.MAINTENANCE_DUE_DATE
  FROM ACTIVITY_DETAIL A,ACTIVITY_MASTER B,MAINTENANCE_SCHEDULE C,   INSTRUMENT_MASTER D
  WHERE A.PLAN_ID = B.PLAN_ID and D.instrument_no=C.instrument_no and   C.plan_id=B.plan_id and  C.activity_id=A.activity_id 
    AND (C.INSTRUMENT_NO,C.PLAN_ID,C.ACTIVITY_ID,C.MAINTENANCE_DUE_DATE)  =(SELECT E.INSTRUMENT_NO,E.PLAN_ID,E.ACTIVITY_ID,
    max(E.MAINTENANCE_DUE_DATE) FROM MAINTENANCE_SCHEDULE E
    where C.PLAN_ID = E.PLAN_ID and C.instrument_no=E.instrument_no and     C.activity_id=E.activity_id group by E.INSTRUMENT_NO,E.PLAN_ID,E.ACTIVITY_ID
      ) and  trunc(c.maintenance_due_date) between To_Date('1-NOV-2019','DD-MON-RRRR') and To_Date('5-NOV-2019','DD-MON-RRRR')
      and d.P_MANITENANCE_REQ<>'N';

我按如下所示进行了修改,但得到了170万行。实际数据只有118行。

SELECT E.Emp_Name, D.Prepared_By, D.location, C.INSTRUMENT_NO, D.EQP_SRL_NO, D.INSTRUMENT_NAME, B.PLAN, A.DETAIL, C.MAINTENANCE_FREQ, C.PERIOD, 
        C.MAINTAIN_ON_DUEDATE,C.MAINTENANCE_DUE_DATE
      FROM ACTIVITY_DETAIL A,ACTIVITY_MASTER B,MAINTENANCE_SCHEDULE C,   INSTRUMENT_MASTER D, Emp_Master E
      WHERE (E.Emp_Initial = D.Prepared_By) or (TO_CHAR(E.Emp_No) = D.Prepared_By) and A.PLAN_ID = B.PLAN_ID and D.instrument_no=C.instrument_no and   C.plan_id=B.plan_id and  C.activity_id=A.activity_id 
        AND (C.INSTRUMENT_NO,C.PLAN_ID,C.ACTIVITY_ID,C.MAINTENANCE_DUE_DATE)  =(SELECT E.INSTRUMENT_NO,E.PLAN_ID,E.ACTIVITY_ID,
        max(E.MAINTENANCE_DUE_DATE) FROM MAINTENANCE_SCHEDULE E
        where C.PLAN_ID = E.PLAN_ID and C.instrument_no=E.instrument_no and     C.activity_id=E.activity_id group by E.INSTRUMENT_NO,E.PLAN_ID,E.ACTIVITY_ID
          ) and  trunc(c.maintenance_due_date) between To_Date(P_FROM_DATE,'DD-MON-RRRR') and To_Date(P_TO_DATE,'DD-MON-RRRR')
          and d.P_MANITENANCE_REQ<>'N';

1 个答案:

答案 0 :(得分:2)

由于第二个查询的连接条件松散或缺失,因此得到了成千上万的“重复项”,这使结果集成为行的乘积。 (如果仔细观察结果集,您可能会发现它们不是完全重复的;相反,它们是所有选定值的排列。)

您已添加一个新表Emp_Master E,并希望通过两个条件之一将其连接到INSTRUMENT_MASTER D。您是这样编写联接的:

WHERE (E.Emp_Initial = D.Prepared_By) 
or (TO_CHAR(E.Emp_No) = D.Prepared_By)

我的猜测是流氓OR是元凶。如果用括号括起该条件,则产品将折叠。

WHERE (E.Emp_Initial = D.Prepared_By 
       or TO_CHAR(E.Emp_No) = D.Prepared_By)