使用oracle查找查询或实现以下要求的方法

时间:2017-10-28 20:21:54

标签: sql oracle select

使用oracle寻找解决方案或实现以下要求的方法

我有两个表TABLE A和TABLE B其中表A中的主键是 表B中的外键

目标是编写查询以从表A和表A中的每一行中选择行 从子表B中选择表A的主键与外键匹配的行 表B

表A

col1.PK     col2        col3        col4         col5       col6
AXXXXX      AXXXX       QQQQ        XXXX         XXXXa      xxxxa
BXXXXX      BXXXX       QQQX        XXXX         XXXXB      vvvvb
CXXXXX      CXXXX       QQQC        XXXX         XXXXD      xxxxd

表B

colb.PK     col1.fk     col3        col4         col5       col6
AXXXXX      AXXXX       QQQQ        XXXX         XXXXa      xxxxa
BXXXXX      BXXXX       QQQX        XXXX         XXXXB      vvvvb
CXXXXX      CXXXX       QQQC        XXXX         XXXXD      xxxxd

最终输出

colAB1      colAB2      colAB3      colAB4       colAB5     colAB6
AXXXXX      AXXXX       QQQQ        XXXX         XXXXa      xxxxa  ---- Parent RECORD FROM TABLE A
AXXXXX      AXXXX       QQQQ        XXXX         XXXXa      xxxxa  ----- child record ( matching child records)
BXXXXX      BXXXX       QQQX        XXXX         XXXXB      vvvvb  ----- child record ( matching child records)
CXXXXX      CXXXX       QQQC        XXXX         XXXXD      xxxxd  ----- child record ( matching child records)

colAB1      colAB2      colAB3      colAB4       colAB5     colAB6
BXXXXX      BXXXX       QQQX        XXXX         XXXXB      vvvvb  ---- Parent RECORD FROM TABLE A
AXXXXX      AXXXX       QQQQ        XXXX         XXXXa      xxxxa  ----- child record ( matching child records)
BXXXXX      BXXXX       QQQX        XXXX         XXXXB      vvvvb  ----- child record ( matching child records)
CXXXXX      CXXXX       QQQC        XXXX         XXXXD      xxxxd  ----- child record ( matching child records

colAB1      colAB2      colAB3      colAB4       colAB5     colAB6
CXXXXX      CXXXX       QQQC        XXXX         XXXXD      xxxxd  ---- Parent RECORD FROM TABLE A
AXXXXX      AXXXX       QQQQ        XXXX         XXXXa      xxxxa  ----- child record ( matching child records)
BXXXXX      BXXXX       QQQX        XXXX         XXXXB      vvvvb  ----- child record ( matching child records)
CXXXXX      CXXXX       QQQC        XXXX         XXXXD      xxxxd  ----- child record ( matching child records)

取值 对于表A中的每一行,表B中将有三个匹配的行

1 个答案:

答案 0 :(得分:0)

这样的事情:

select *
from ((select a.*, 1 as is_a
       from a
      ) union all
      (select b.*, 0 as is_a
       from b
      )
     ) ab
order by (case when is_a then col1 else col2 end), -- col2 is the foreign key reference
         is_a desc,
         col1