选择带有in关键字的语句不能按预期工作

时间:2015-06-02 13:38:43

标签: oracle

我有奇怪的问题。 我在表A中有一个列,其中我以字符串格式joe,rose,chandler存储一个值。 joe,rose和chandler对应于表B中的1,2 n 3。

SELECT number
FROM B
WHERE name IN
 (SELECT CONCAT(CONCAT('''',name),'''') AS name
 FROM
  (SELECT REPLACE(info_value, ',' ,''',''') AS name
 FROM B
 )
);

以下sql导致'joe','rose','chandler'

      (SELECT CONCAT(CONCAT('''',name),'''') AS name
       FROM
      (SELECT REPLACE(info_value, ',' ,''',''') AS name
       FROM B
      )
    );

但它没有检索任何内容。

但是,如果我将结果集直接传递给同一个sql,如下所示,那么它工作正常。

    SELECT number
     FROM B
    WHERE name IN('joe','rose','chandler')

如果有人对此有任何指示,请告诉我。

1 个答案:

答案 0 :(得分:0)

SQL Fiddle

Oracle 11g R2架构设置

如果您创建一个将列表拆分为集合的函数:

CREATE OR REPLACE FUNCTION splitList(
  str   VARCHAR2,
  delim VARCHAR2 DEFAULT ','
) RETURN SYS.ODCIVARCHAR2LIST DETERMINISTIC
AS
  o_list SYS.ODCIVARCHAR2LIST;
  p_prev NUMBER(4,0) := 1;
  p_next NUMBER(4,0);
BEGIN
  o_list := SYS.ODCIVARCHAR2LIST();
  IF ( str IS NULL ) THEN
    NULL;
  ELSIF ( delim IS NULL ) THEN
    o_list.EXTEND( 1 );
    o_list(1) := str;
  ELSE
    p_next := INSTR( str, delim, p_prev, 1 );
    WHILE ( p_next > 0 ) LOOP
      IF ( p_next > p_prev ) THEN
        o_list.EXTEND( 1 );
        o_list( o_list.COUNT ) := SUBSTR( str, p_prev, p_next - p_prev );
      END IF;
      p_prev := p_next + LENGTH( delim );
      p_next := INSTR( str, delim, p_prev, 1 );
    END LOOP;
    IF ( p_prev <= LENGTH( str ) ) THEN
      o_list.EXTEND( 1 );
      o_list( o_list.COUNT ) := SUBSTR( str, p_prev );
    END IF;
  END IF;
  RETURN o_list;
END splitList;
/

然后你可以这样做:

CREATE TABLE TableA ( info_value ) AS
SELECT 'joe,rose,chandler' FROM DUAL
/

CREATE TABLE TableB ( "number", name ) AS
          SELECT 1, 'joe' FROM DUAL
UNION ALL SELECT 2, 'rose' FROM DUAL
UNION ALL SELECT 3, 'alice' FROM DUAL
UNION ALL SELECT 4, 'chandler' FROM DUAL
UNION ALL SELECT 5, 'bob' FROM DUAL
/

查询1

SELECT "number"
FROM   TableB
WHERE  name IN ( SELECT COLUMN_VALUE
                 FROM   TABLE(
                          splitList(
                            ( SELECT info_value
                              FROM TableA
                            )
                          )
                        )
               )

<强> Results

| number |
|--------|
|      1 |
|      2 |
|      4 |