未名Q

此生若能得幸福安稳,谁又愿颠沛流离。

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: 订阅 订阅 :: 管理 ::
create table TEMP_A
(
  id        NUMBER,
  parent_id NUMBER,
  text      VARCHAR2(10),
  type      CHAR(1)
);
insert into TEMP_A (ID, PARENT_ID, TEXT, TYPE) values (1, null, null, 'M');
insert into TEMP_A (ID, PARENT_ID, TEXT, TYPE) values (2, 1, 'b', 'S');
insert into TEMP_A (ID, PARENT_ID, TEXT, TYPE) values (3, null, null, 'M');
insert into TEMP_A (ID, PARENT_ID, TEXT, TYPE) values (4, null, 'd', 'S');
insert into TEMP_A (ID, PARENT_ID, TEXT, TYPE) values (5, 3, 'e', 'S');
insert into TEMP_A (ID, PARENT_ID, TEXT, TYPE) values (6, null, 'f', 'M');
insert into TEMP_A (ID, PARENT_ID, TEXT, TYPE) values (7, 3, 'g', 'S');
insert into TEMP_A (ID, PARENT_ID, TEXT, TYPE) values (8, null, 'h', 'B');

SQL> select t.* from TEMP_A t;

        ID  PARENT_ID TEXT       TYPE
---------- ---------- ---------- ----
         1                       M
         2          1 b          S
         3                       M
         4            d          S
         5          3 e          S
         6            f          M
         7          3 g          S
         8            h          B

8 rows selected

SELECT *  FROM TEMP_A m LEFT JOIN temp_a s ON m.id=s.parent_id AND s.type='S' AND s.parent_id IS NOT NULL WHERE m.type='M';

-- 直接带出
SELECT m.id,
(CASE WHEN m.parent_id IS NULL THEN s.id ELSE m.parent_id END) AS s_id,
(CASE WHEN m.text IS NULL THEN s.text ELSE m.text END) AS text
 FROM TEMP_A m LEFT JOIN temp_a s ON m.id=s.parent_id AND s.type='S' WHERE m.type='M';

-- 把id做为一个虚拟表使用
SELECT (CASE WHEN s.id IS NULL THEN m.id ELSE s.id END) AS s_id
,(CASE WHEN s.parent_id IS NULL THEN m.id ELSE s.parent_id END) AS m_id
 FROM TEMP_A m LEFT JOIN temp_a s ON m.id=s.parent_id AND s.type='S' AND s.parent_id IS NOT NULL WHERE m.type='M';
posted on 2020-07-08 14:01  未名Q  阅读(168)  评论(0编辑  收藏  举报