0

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

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

我不是 Oracle 用户,我需要获取将获取 FORM_A 数据和 FORM_B 的所有 FORM,但我需要从两个表中按名称对其进行排序。"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)...

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

4

2 回答 2

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
于 2013-02-18T11:01:19.570 回答
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
于 2013-02-18T11:02:02.263 回答