基于子字符串的Oracle查询选择

时间:2018-10-16 02:21:03

标签: sql oracle oracle11g

已执行以下命令:

CREATE TABLE film (
  film_id NUMBER(5) NOT NULL,
  title varchar2(255),
  description varchar2(255),
  release_year NUMBER(4) DEFAULT NULL,
  language_id NUMBER(3) NOT NULL,
  original_language_id NUMBER(3) DEFAULT NULL,
  rental_duration NUMBER(3) DEFAULT 3 NOT NULL,
  rental_rate NUMBER(4,2) DEFAULT '4.99',
  length NUMBER(5) DEFAULT NULL,
  replacement_cost NUMBER(5,2) DEFAULT '19.99' NOT NULL,
  rating varchar2(8) DEFAULT 'G',
  special_features varchar2(255) DEFAULT NULL
);

假设已填充大量数据。

我想构造一个查询以选择头200个电影标题(按字母升序 ),其中电影以Boat进行。假定影片位置包含在影片表和属性,说明中。另外,它总是在单词in第一次出现之后,并在句子的末尾结束。例如在以下电影说明中:

​A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher 
in The Canadian Rockies

位置为The Canadian Rockies

只要该位置包含单词Boat,就可以了。 Boat可以是任何船,例如 U型船 JET船

2 个答案:

答案 0 :(得分:1)

您可以结合使用instr函数将boatin组合在一起:

select film_description
  from
(
with t(film_description) as
(
 select '... a Teacher in The Canadian Rockies' from dual union all
 select 'Boat on the river' from dual union all
 select 'on the river in a Boat' from dual union all
 select 'on the river in a U-Boat' from dual union all
 select 'on the river in a JET Boat' from dual    
)
select t.film_description, dense_rank() over (order by t.film_description) as dr
  from t
 where instr(lower(t.film_description),'boat') > instr(t.film_description,' in ')
   and instr(t.film_description,' in ') > 0
)   
where dr <= 200;

,或者如果您的 Oracle DB 版本为 12c ,则可以使用以下命令:

with t(film_description) as
(
 ................
 ................ 
 select '... a Teacher in The Canadian Rockies' from dual union all
 select 'Boat on the river' from dual union all
 select 'on the river in a Boat' from dual union all
 select 'on the river in a U-Boat' from dual union all
 select 'on the river in a JET Boat' from dual    
)
select t.film_description
  from t
 where instr(lower(t.film_description),'boat') > instr(t.film_description,' in ')
   and instr(t.film_description,' in ') > 0
fetch first 200 rows only;

Rextester Demo

答案 1 :(得分:0)

也许查询看起来像这样:

SELECT * 
FROM "FILM" 
WHERE UPPER("DESCRIPTION") LIKE '%IS%BOAT%'
AND ROWNUM<200;