在数据库中实现类似'20问题'的向导

时间:2008-09-02 15:19:33

标签: sql oracle database-design

我希望实现一个数据驱动向导,其中问题树存储在Oracle数据库中。什么是用于使数据库部分灵活(即易于添加新的问题路径)而不牺牲性能方面的最佳模式?

1 个答案:

答案 0 :(得分: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如何用于确定我们在树下的距离,然后我用它来缩进数据以显示结构。