Oracle 11g - 使用m到n关系表连接多行数据

时间:2012-02-14 15:58:35

标签: sql oracle plsql

我可能有一些简单的问题,但我仍然无法弄清楚如何让事情发挥作用。

我有三个包含这些重要字段的表格:

  1. 规则 - RuleOID
  2. RuleToModificationReason - RuleOID,MdfnReasonOID
  3. ModificationReason - MdfnReasonOID,MdfnTyp(CREATION或DELETION),MdfnDetail
  4. 并且f.e。我有这些数据:

    1. 规则 - RuleOID = 1
    2. RuleToModificationReason
      • RuleOID = 1,MdfnReasonOID = 1
      • RuleOID = 1,MdfnReasonOID = 2
    3. ModificationReason
      • MdfnReasonOID = 1,MdfnTyp ='CREATION',MdfnDetail ='创作细节'
      • MdfnReasonOID = 2,MdfnTyp ='DELETION',MdfnDetail ='删除详情'
    4. 我希望在一行上输出用于创建和删除规则oid。

      f.e。 :RuleOID,创建详细信息,删除详细信息。

      我可以将它加载到两行中,如:

      1. RuleOID,创建详细信息,NULL
      2. RuleOID,NULL,删除详细信息。
      3. 创建和删除原因可以为null。

        甚至可能吗?

3 个答案:

答案 0 :(得分:0)

如果您确定某个规则的大多数始终存在一个创建详细信息,并且大多数给定规则的一个删除详细信息,然后你可以使用子查询:

SELECT Rule.RuleOID,
       ( SELECT MdfnDetail
           FROM ModificationReason
          WHERE MdfnType = 'CREATION'
            AND MdfnReasonOID IN
                 ( SELECT MdfnReasonOID
                     FROM RuleToModificationReason
                    WHERE RuleOID = Rule.RuleOID
                 )
       ) AS CreationReason,
       ( SELECT MdfnDetail
           FROM ModificationReason
          WHERE MdfnType = 'DELETION'
            AND MdfnReasonOID IN
                 ( SELECT MdfnReasonOID
                     FROM RuleToModificationReason
                    WHERE RuleOID = Rule.RuleOID
                 )
       ) AS DeletionReason
  FROM Rule
;

(也可以用JOIN来实现这一点,但这样做会更加棘手。)

答案 1 :(得分:0)

它会对你有用吗?

SELECT a.RuleOID, 
CASE
  WHEN b.MdfnTyp = 'CREATION' THEN b.MdfnDetail
  ELSE NULL -- can omit, case has default "else null"
END AS creation_detail,
CASE
  WHEN b.MdfnTyp = 'DELETION' THEN b.MdfnDetail
  ELSE NULL -- can omit, case has default "else null"
END AS deletion_detail

RuleToModificationReason a
INNER JOIN ModificationReason b ON (a.MdfnReasonOID = b.MdfnReasonOID)

注意:规则表已按目的跳过(假设参照完整性由约束强制执行),因为您不使用该表中的任何字段

答案 2 :(得分:0)

select crtr.RuleOID RuleOID, crt.MdfnDetail Creation_detail, dlt.MdfnDetail Deletion_detail
from ModificationReason crt, ModificationReason dlt, RuleToModificationReason crtr, RuleToModificationReason dltr
where crt.MdfnTyp = 'CREATION' and dlt.MdfnTyp = 'DELETION'
and crt.MdfnReasonOID = crtr.MdfnReasonOID
and dlt.MdfnReasonOID = dltr.MdfnReasonOID
and crtr.RuleOID = dltr.RuleOID   

(无法检查)