从oracle中的特定列检索记录

时间:2016-04-18 20:51:12

标签: sql regex oracle oracle10g pattern-matching

S.NO     id        Pid
1        123       PAQ123  
2        433       WSD3FF  
3        565       PAS45E  
4        123       PAQ123X  
5        433       WSD3FFY  
6        123       PAQ123Z

假设以上是数据库中的样本记录。

现在我想在数据库中找出是否有任何单词(例如PAQ123)重复一些前缀/后缀,如(PAQ123X,PAQ123Z)。

如何编写导致上述列表方案的查询?

1 个答案:

答案 0 :(得分:0)

Oracle安装程序

CREATE TABLE table_name ( S_NO, id, Pid ) AS
SELECT 1, 123, 'PAQ123' FROM DUAL UNION ALL
SELECT 2, 433, 'WSD3FF' FROM DUAL UNION ALL  
SELECT 3, 565, 'PAS45E' FROM DUAL UNION ALL
SELECT 4, 123, 'PAQ123X' FROM DUAL UNION ALL
SELECT 5, 433, 'WSD3FFY' FROM DUAL UNION ALL
SELECT 6, 123, 'PAQ123Z' FROM DUAL;

<强>查询

SELECT *
FROM   (
  SELECT t.*,
         ( SELECT COUNT(*)
           FROM   table_name x
           WHERE  t.id = x.id
           AND    LENGTH( t.Pid ) < LENGTH( x.pid )
           AND    INSTR( x.Pid, t.Pid ) = 1 ) AS num_matches
  FROM   Table_name t
)
WHERE num_matches > 0;

<强>输出

      S_NO         ID PID     NUM_MATCHES
---------- ---------- ------- -----------
         1        123 PAQ123            2 
         2        433 WSD3FF            1 

如果你想获得比赛,那么你可以使用一个集合:

CREATE TYPE stringlist AS TABLE OF VARCHAR2(100);
/

<强>查询

SELECT *
FROM   (
  SELECT t.*,
         CAST(
           MULTISET(
             SELECT PID
             FROM   table_name x
             WHERE  t.id = x.id
             AND    LENGTH( t.Pid ) < LENGTH( x.pid )
             AND    INSTR( x.Pid, t.Pid ) = 1
           )
           AS stringlist
         ) AS matches
  FROM   Table_name t
)
WHERE matches IS NOT EMPTY;

或(因为我不确定MULTISET是否在10g中):

SELECT *
FROM   (
  SELECT t.*,
         CAST(
           ( 
             SELECT COLLECT( PID )
             FROM   table_name x
             WHERE  t.id = x.id
             AND    LENGTH( t.Pid ) < LENGTH( x.pid )
             AND    INSTR( x.Pid, t.Pid ) = 1
           )
           AS stringlist
         ) AS matches
  FROM   Table_name t
)
WHERE matches IS NOT EMPTY;

<强>输出

      S_NO         ID PID     MATCHES 
---------- ---------- ------- ------------------------------------
         1        123 PAQ123  TEST.STRINGLIST('PAQ123X','PAQ123Z')
         2        433 WSD3FF  TEST.STRINGLIST('WSD3FFY')