2013-02-18 59 views
0

我有這個數據庫。對於初學者,我沒有創建這個數據庫,我不能改變結構,所以我必須處理它。如何通過不同表格中的兩個相同屬性進行排序?

+------+ +--------+ +--------+ 
| FORM | | FORM_A | | FORM_B | 
+------+ +--------+ +--------+ 
| id | | form_id| | form_id| 
      | name | | name | 

我不是一個Oracle用戶,我需要獲得所有形式,其中我會得到FORM_A DATAS以及FORM_B,但我需要通過名稱從兩個表來訂購吧。 「name」與FORM_A和FORM_B是同一種數據,太糟糕了,它不在FORM中。

Exemple : 
FORM_A = [a, b, d, f] 
FORM_B = [e, c, g] 
FORM datas must be ordered as FORM_A(a), FORM_A(b), FORM_B(c), FORM_A(d), FORM_B(e)... 

起初,我想我會用一些人工的循環訂購它,但我不知道是否有下令將倍數表一起的方式,和其他的沒有後一個?

回答

0

我假設下表內容:

 FORM    FORM_A    FORM_B 
+----+--------+ +------+---------+ +------+---------+ 
| ID | NAME | | NAME | FORM_ID | | NAME | FORM_ID | 
+----+--------+ |+-----+---------+ |+-----+---------+ 
| 1 | First | | a |  1 | | e |  3 | 
| 2 | Second | | b |  2 | | c |  4 | 
| 3 | Third | | d |  2 | | g |  5 | 
| 4 | Fourth | | f |  3 | +------+---------+ 
| 5 | Fifth | +------+---------+ 
+----+--------+ 

您可以使用UNION從兩個表中選擇,前提是兩個表具有相同的列結構:

SELECT FORM_A.form_id, FORM_A.name 
FROM FORM_A 
UNION ALL 
SELECT FORM_B.form_id, FORM_B.name 
FROM FORM_B 
ORDER BY name; 

    FORM_ID NAME 
---------- ----- 
     1 a 
     2 b 
     4 c 
     2 d 
     3 e 
     3 f 
     5 g 

通過加入FORM_IDFORM表,然後您從FORM獲得相應的行:

SELECT ab.Name AS AB, f.Name AS DATA 
FROM (SELECT FORM_A.form_id, FORM_A.name 
     FROM FORM_A 
     UNION ALL 
     SELECT FORM_B.form_id , FORM_B.name 
     FROM FORM_B 
     ORDER BY name) ab 
     JOIN FORM f ON f.id=ab.FORM_ID; 

AB DATA 
----- ---------- 
a  First 
b  Second 
c  Fourth 
d  Second 
e  Third 
f  Third 
g  Fifth 
0

你可以

select * 
     from (select id, null as name from form union all 
      select id, name from formA union all 
      select id, name from formB 
      ) temp 
     order by temp.name 
相關問題