如何通过不同表中的两个相同属性进行排序?

时间:2013-02-18 10:57:13

标签: sql oracle

我有这个DB。对于初学者,我没有创建这个数据库,我无法改变结构,所以我必须处理它。

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

我不是Oracle用户,我需要获取所有FORM,我将获得FORM_A数据以及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)...

起初我认为我必须手动订购一些循环,但我想知道是否有办法从多个表一起订购,而不是一个接一个地订购?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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