将参数值传递给like

时间:2018-08-31 14:19:23

标签: sql oracle

create table ter (
  ID number, 
  category varchar2(250 byte),
  name varchar2(250 byte)
); 

insert into ter values (1, 'amd-visual theraphy','john');
insert into ter values (1, 'amd-visual theraphy','mike');
insert into ter values (2, 'amd-autmatic theraphy','mike');
insert into ter values (3, 'amd-autmatic theraphy','drane');
insert into ter values (3, 'cmd autmatic theraphy', 'traverse');
insert into ter values (3, 'amd-dramatic theraphy','drane');
insert into ter values (3, 'cmd-dropertic theraphy', 'traverse');
insert into ter values (5,'qwd-dropertic visual-theraphy','drones');
insert into ter values (5,'qwd-aromatic-theraphy','drones');
insert into ter values (3, 'other', 'traverse');
insert into ter values (3, 'other', 'traverse');

1:&category为空,显示所有记录

2:&category不为null,并且如果我输入category = visual,autmatic然后分别显示

3&category不为null,并且如果我输入category = dramatic,它将显示dramtic和dropertic,而忽略其他结果;

用户需要看到且忽略戏剧性和浮夸性的要求,而忽略部分值是否与视觉和自动包含匹配

如何获得此结果 这就是给我解决方案的原因,但我仍然想忽略包含dropetic的视觉

   select *
    from   ter t cross join (select '&category' as my_categ from dual) m
 where  m.my_categ is null
or  m.my_categ in ('visual', 'autmatic', 'dramtic') and t.category like '%' 
 || m.my_categ || '%'
 or  m.my_categ = 'dramtic' and t.category like '%dropertic%' ;

1 个答案:

答案 0 :(得分:0)

我会稍微更改您的数据模型。 与其将类别另存为以空格分隔的字符串,不如将它们移至单独的表中。

create table category(
  ter_id number,
  name varchar(250 bytes)
);

其中ter_idID列中的ter相同。

此表应包含以下记录:

insert into category values (1, 'amd-visual');
insert into category values (1, 'therapy');
-- etc.

在您的查询上方隐含以下内容:

select t.*, c.* 
from ter t, category c
where t.id = c.ter_id
  and category in ('therapy', 'visual');
  -- etc...

如果您确实需要满足条件:

  

如果类别为空,则显示所有记录

添加即可轻松实现 将空类别为name的记录记录到表category中:

insert into category values (1, null);
insert into category values (2, null);

-等等