将逗号分隔列表拆分为临时 table

splitting comma separated list into a temp table

我想将以下 IN 查询转换为内部连接查询:

select country, name, rank from table person_details 
   where country in ('india','USA','australia') 
   and   name in ('tom', 'jill', 'jack') 
   and   rank in ('first', 'third', 'fifith');

我有两个问题:

  1. 这个 table 很大,所以将这个 IN 查询更改为内部连接会加快速度。

  2. 在某些临时 table 中将此逗号分隔列表拆分为一列的最佳方法是什么。我看过很多正则表达式的例子,但它们看起来太复杂和庞大了。

我正在使用 Oracle 11g 数据库。

Table 快照:

Id   name   country   rank
 1    tom    india     first
 2    jill   USA      second
 3    jack   aus       first

select country, name, rank from table person_details

查询在语法上不正确。您不需要关键字 TABLE。只要做:

select country, name, rank from person_details

严格来说,您的 table 未 标准化 。您不应在单个列中存储多个值。迟早你会看到性能问题。重新设计 table 并将值存储在单独的列中永远不会太晚。

话虽如此,有很多方法可以将逗号分隔的字符串拆分成行。这是在 CONNECT BY 子句中使用 REGEXP_SUBSTRINSTR 的一种简单方法:

SQL> WITH DATA AS(
  2  select q'['india','USA','australia']' countries,
  3  q'['tom', 'jill', 'jack']' names,
  4  q'['first', 'third', 'fifth']' ranks
  5  from dual
  6  )
  7  SELECT regexp_substr(translate(countries,'''',' '), '[^,]+', 1, LEVEL) countries,
  8  trim(regexp_substr(translate(names,'''',' '), '[^,]+', 1, LEVEL)) names,
  9  trim(regexp_substr(translate(ranks,'''',' '), '[^,]+', 1, LEVEL)) ranks
 10  FROM DATA
 11  CONNECT BY instr(countries, ',', 1, LEVEL - 1) > 0
 12  /

COUNTRIES                 NAMES                 RANKS
------------------------- --------------------- -------------------------
 india                    tom                   first
 USA                      jill                  third
 australia                jack                  fifth

SQL>

我在我的文章ORACLE DELIMITED STRING MANIPULATION中展示了其他方法。