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';
Q 说:
欢迎转载,但请注明内容的来源或URL;
“[转]”篇章,必须保留原始来源且勿添加本blog指向。
欢迎转载,但请注明内容的来源或URL;
“[转]”篇章,必须保留原始来源且勿添加本blog指向。