如何查找没有预管“基础”值的项目

时间:2017-10-10 11:06:14

标签: sql oracle split delimited-text

我在表(部分)中有一个带有列(obj_id)的数据库,其中我应该有一个12345的obj_id,它是另一行的集合,它将具有12345 |。

所以:

select obj_id from parts where obj_id like '12345%';
12345
12345|A
12345|B
12345|77

现在,有人违反了指南,并输入了一些带有管道值的项目,但没有管道的基础值(例如12378 | J,12378 | 8但不是12378)。

我需要知道如何编写SQL查询来查找表中没有匹配的基本(非管道)值的管道值。

1 个答案:

答案 0 :(得分:0)

如果没有一些实际的样本数据可以使用它,很难知道你真正想要的是什么。低于2个可能有帮助的查询,但也许它会让您记下样本数据的有用程度:

请参阅此处SQL Fiddle

CREATE TABLE PARTS
    (id int, OBJ_ID varchar2(200))
;

INSERT ALL 
    INTO PARTS (id, OBJ_ID)
         VALUES (1,'12345 12345|A 12345|B 12345|77')
    INTO PARTS (id, OBJ_ID)
         VALUES (2,'12346|A 12346|B 12346|77')
    INTO PARTS (id, OBJ_ID)
         VALUES (3,'12378|J, 12378|8')
    INTO PARTS (id, OBJ_ID)
         VALUES (4,NULL)
    INTO PARTS (id, OBJ_ID)
         VALUES (5,'fred. wilma, barney, betty')
SELECT * FROM dual
;

查询1

select
*
from PARTS p
where instr(p.OBJ_ID,' ') > instr(p.OBJ_ID,'|')

<强> Results

| ID |                     OBJ_ID |
|----|----------------------------|
|  2 |   12346|A 12346|B 12346|77 |
|  3 |           12378|J, 12378|8 |
|  5 | fred. wilma, barney, betty |

查询2

select
       id, rn_a, regexp_substr (OBJ_ID_SPLIT, '[^|]+', 1, rn_b) as OBJ_ID_SPLIT
from (
      select 
             p.id, c1.rn_a, regexp_substr (p.OBJ_ID, '[^ ]+', 1, c1.rn_a) as OBJ_ID_SPLIT
      from PARTS p
      cross join (select rownum as rn_a
                   from (select max(length (regexp_replace (OBJ_ID, '[^|]+'))) + 1 as mx
                         from PARTS
                        )
                connect by level <= mx) c1
      where p.OBJ_ID like '%|%'       
      ) d
cross join (select 1 rn_b from dual union all select 2 from dual) c2
order by id, rn_a

<强> Results

| ID | RN_A | OBJ_ID_SPLIT |
|----|------|--------------|
|  1 |    1 |        12345 |
|  1 |    1 |       (null) |
|  1 |    2 |        12345 |
|  1 |    2 |            A |
|  1 |    3 |        12345 |
|  1 |    3 |            B |
|  1 |    4 |        12345 |
|  1 |    4 |           77 |
|  2 |    1 |        12346 |
|  2 |    1 |            A |
|  2 |    2 |        12346 |
|  2 |    2 |            B |
|  2 |    3 |        12346 |
|  2 |    3 |           77 |
|  2 |    4 |       (null) |
|  3 |    1 |        12378 |
|  3 |    1 |           J, |
|  3 |    2 |        12378 |
|  3 |    2 |            8 |
|  3 |    3 |       (null) |
|  3 |    4 |       (null) |