查詢字串中連續出現的字元

flzhang發表於2016-03-22

根據使用者需求需要查詢字串中連續出現的字元

'mn,asdfs,opq,dfasf,abc,asdlfj,defg' 'DF,RST',要求找出兩個字串中連續出現的字元

這裡兩個字串資料相當於表中的兩行資料,具體資料用sql構造。對於這種需求的sql主要涉及兩塊,一個是如何找出字串中被,號

分割的字元。一個是如何判斷字元是連續的字元。

1 找出字串中所有被,號分割出的字元




SELECT regexp_substr(teststr,'[^,]+',1,level) teststr

          FROM (

                SELECT 'mn,asdfs,opq,dfasf,abc,asdlfj,defg' teststr

                      ,1 id1

                FROM dual

                UNION ALL

                SELECT 'DF,RST' teststr

                      ,2 id1

                FROM DUAL) t

          connect by level <20 

          AND PRIOR id1 = id1

          AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL;









這裡第一行資料和第二行資料明顯產生遞迴關係,因此需要PRIOR id1 = id1 來過濾不必要的遞迴步驟



2 而查詢字元是否連續的,可以用如下sql查詢出所有字元的組合




select ss

           from (select replace(sys_connect_by_path(c, ','), ',') ss

                   from (select rownum i, chr(65 + rownum - 1) c

                           from dual

                         connect by rownum <= 26)

                 connect by prior i = i - 1)

          where length(ss) >= 2;


3 最後用分割出的每個字元單元和連續字元的組合判斷,查詢出所有屬於連續字元的資料即所要結果


select teststr,
 
        regexp_substr(upper(teststr), '[A-Z]{2,10}') reqstr

   from ( SELECT regexp_substr(teststr,'[^,]+',1,level) teststr
          FROM (
                SELECT 'mn,asdfs,opq,dfasf,abc,asdlfj,defg' teststr
                      ,1 id1
                FROM dual
                UNION ALL
                SELECT 'DF,RST' teststr
                      ,2 id1
                FROM DUAL) t
          connect by level <20 
          AND PRIOR id1 = id1
          AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL
         )   
  
  where regexp_substr(upper(teststr), '[A-Z]{2,10}') in

        (select ss

           from (select replace(sys_connect_by_path(c, ','), ',') ss

                   from (select rownum i, chr(65 + rownum - 1) c

                           from dual

                         connect by rownum <= 26)

                 connect by prior i = i - 1)

          where length(ss) >= 2);

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/750077/viewspace-2061742/,如需轉載,請註明出處,否則將追究法律責任。

相關文章