在数据库中实现类似于" 20个问题"的向导

时间:2020-03-05 18:46:31  来源:igfitidea点击:

我希望使用存储在Oracle数据库中的问题树来实现数据驱动的向导。在不牺牲太多性能的情况下,哪种最佳方案可用于使数据库部分更灵活(即易于添加新的问题路径)?

解决方案

回答

我们可以使用引用同一张表的外键(通常称为"猪耳"关系)来构建树结构。然后,我们可以使用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来确定树到底有多远,然后我将其用于缩进数据以显示结构。