我希望使用存储在 Oracle 数据库中的问题树来实现一个数据驱动的向导。在不牺牲太多性能的情况下,使数据库部分灵活(即易于添加新的问题路径)的最佳模式是什么?
问问题
1386 次
1 回答
0
您可以使用引用同一个表的外键构建树结构(通常称为“猪耳朵”关系)。然后可以使用 CONNECT BY 语法遍历树。这是一个简单的例子:
SQL> create table qs
2 ( q_id integer primary key
3 , parent_q_id integer references qs
4 , parent_q_answer varchar2(1)
5 , q_text varchar2(100)
6* );
Table created.
SQL> insert into qs values (1, null, null, 'Is it bigger than a person?');
1 row created.
SQL> insert into qs values (2, 1, 'Y', 'Does it have a long neck?');
1 row created.
SQL> insert into qs values (3, 2, 'Y', 'It is a giraffe');
1 row created.
SQL> insert into qs values (4, 2, 'N', 'It is an elephant');
1 row created.
SQL> insert into qs values (5, 1, 'N', 'Does it eat cheese?');
1 row created.
SQL> insert into qs values (6, 5, 'Y', 'It is a mouse');
1 row created.
SQL> insert into qs values (7, 5, 'N', 'It is a cat');
1 row created.
SQL> commit;
Commit complete.
SQL> select rpad(' ',level*4,' ')||parent_q_answer||': '||q_text
2 from qs
3 start with parent_q_id is null
4 connect by prior q_id = parent_q_id;
RPAD('',LEVEL*4,'')||PARENT_Q_ANSWER||':'||Q_TEXT
------------------------------------------------------------------------------------------------------------------------------
: Is it bigger than a person?
Y: Does it have a long neck?
Y: It is a giraffe
N: It is an elephant
N: Does it eat cheese?
Y: It is a mouse
N: It is a cat
7 rows selected.
请注意如何使用特殊关键字 LEVEL 来确定我们在树的下方有多远,然后我用它来缩进数据以显示结构。
于 2008-09-18T10:44:23.700 回答