数据库设计中单个字段多值的处理

         在数据库设计中,有一种情况是比较头痛的,就是一条业务数据有一个字段是多个值拼起来的,如一个设备有多个维护部门。

create table devcie

(

   devcie_id number,

   vindicate_dept_id  varchar2(100)

);

insert into devcie values(1,'11');

insert into devcie values(2,'22');

insert into devcie values(3,'1111');

insert intodevcie values(4,'33');

insert into devcie values(5,'1111;22');

insert into devcie values(6,'11;22');

insert intodevcie values(7,'11;22;33');

insert into devcie values(8,'22;33');

commit;

问题出来了,如果要查dept_id为11的部门,下面看我们查一下:

SQL> select * from devcie where vindicate_dept_id like '%11%';
 DEVCIE_ID VINDICATE_DEPT_ID
---------- --------------------------------------------------------
         1 11
         3 1111
         5 1111;22

         6 11;22
         7 11;22;33

换一种查询方式:

SQL> select * from devcie where instr(vindicate_dept_id,'11')>0;
 DEVCIE_ID VINDICATE_DEPT_ID
---------- -----------------------------------------------------------
         1 11
         3 1111
         5 1111;22
         6 11;22
         7 11;22;33

在换一种方式,考虑部门只有一个值的情况=‘11’,多个值的情况在最前面like '11;%',在最后面'%;11',在中间'%;11;%',这下全了,执行一下

SQL> select * from devcie where vindicate_dept_id ='11'
    or vindicate_dept_id like '11;%'
    or vindicate_dept_id like '%;11'
   or vindicate_dept_id like '%;11;%';
 DEVCIE_ID VINDICATE_DEPT_ID
---------- --------------------------------------------
         1 11
         6 11;22
         7 11;22;33

崩溃啊,要这么复杂吗?如何解决呢?

update devcie set vindicate_dept_id = ';'||vindicate_dept_id||';';
commit;

SQL> select * from devcie;
 DEVCIE_ID VINDICATE_DEPT_ID
---------- -----------------------------------------
         1 ;11;
         2 ;22;
         3 ;1111;
         4 ;33;
         5 ;1111;22;
         6 ;11;22;
         7 ;11;22;33;
         8 ;22;33;

再次查询为11的部门就没问题了。

SQL> select * from devcie where instr(vindicate_dept_id,';11;')>0;
 DEVCIE_ID VINDICATE_DEPT_ID
---------- --------------------------------------------------------
         1 ;11;
         6 ;11;22;
         7 ;11;22;33;

SQL> select * from devcie where vindicate_dept_id like '%;11;%';
 DEVCIE_ID VINDICATE_DEPT_ID
---------- -----------------------------------------------------------
         1 ;11;
         6 ;11;22;
         7 ;11;22;33;

你可能感兴趣的:(数据库设计)