我需要你的帮助。我希望基于带有oracle SQL的第二个表来从同一个表中union
数据。
表1
id | au_id | data
------------------
1 | 33 | foo
2 | 44 | foo
3 | 34 | foo
4 | 55 | foobar
5 | 55 | fooo
表2
au_id | follow_au_id
-----------------------
33 | 55
结果
au_id | data
----------------
33 | foo
33 | foobar
33 | fooo
44 | foo
34 | foo
55 | foobar
55 | fooo
答案 0 :(得分:1)
你必须使用join
select t1.au_id, t3.data
from table1 t1
join table2 t2 on t1.au_id=t2.au_id
join table1 t3 on t2.follow_au_id = t3.au_id
union
select t1.au_id, t1.data
from table1 t1
答案 1 :(得分:1)
select au_id, data from tbl
union all
select t2.au_id, t1.data from tbl t1 join tbl t2 on t1.au_id = t2.follow_au_id
答案 2 :(得分:1)
您需要加入和 UNION
SELECT t.*
FROM
( SELECT t1.au_id, t1.data FROM table1 t1
UNION ALL
SELECT t2.au_id,
t1.data
FROM table1 t1
JOIN table2 t2
ON t1.au_id = t2.follow_au_id
) t
ORDER BY t.au_id
/
感谢@notulysses指出,这是一个不正确的外连接解决方案。请参阅此SQL Fiddle。
正确的解决方案如下:
例如,
<强>设置强>
SQL> CREATE TABLE Table1
2 (id int, au_id int, data varchar2(6))
3 ;
Table created.
SQL>
SQL> INSERT ALL
2 INTO Table1 (id, au_id, data)
3 VALUES (1, 33, 'foo')
4 INTO Table1 (id, au_id, data)
5 VALUES (2, 44, 'foo')
6 INTO Table1 (id, au_id, data)
7 VALUES (3, 34, 'foo')
8 INTO Table1 (id, au_id, data)
9 VALUES (4, 55, 'foobar')
10 INTO Table1 (id, au_id, data)
11 VALUES (5, 55, 'fooo')
12 SELECT * FROM dual
13 ;
5 rows created.
SQL>
SQL> CREATE TABLE Table2
2 (au_id int, follow_au_id int)
3 ;
Table created.
SQL>
SQL> INSERT ALL
2 INTO Table2 (au_id, follow_au_id)
3 VALUES (33, 55)
4 SELECT * FROM dual
5 ;
1 row created.
SQL>
<强>查询强>
SQL> SELECT t.*
2 FROM
3 ( SELECT t1.au_id, t1.data FROM table1 t1
4 UNION ALL
5 SELECT t2.au_id,
6 t1.data
7 FROM table1 t1
8 JOIN table2 t2
9 ON t1.au_id = t2.follow_au_id
10 ) t
11 ORDER BY t.au_id
12 /
AU_ID DATA
---------- ------
33 foobar
33 fooo
33 foo
34 foo
44 foo
55 fooo
55 foobar
7 rows selected.
SQL>