选择2927 id

时间:2016-06-30 08:49:31

标签: sql oracle toad

我有2927个id的列表。我想得到id列在该列表中的所有行。我怎样才能做到这一点?这是一个逗号分隔的id列表。由于存在1000的限制,因此in语句将不起作用。我已经尝试过这样的解决方案Loop through pre defined values,但它没有达到我的预期。

我正在使用toad,我希望看到datagrid中的行(多行,多列)。

提前致谢!

ID的列表可能如下所示:

  

67,122,173,256,284,285,288,289,291,294,296,298,301,320,346,359,366,425,428,454,528,573,576,584,593,654,654,694,722,838,1833,1976,1979,1979,2002,2004,2005,2045,2083,2109,2114,2126,2126,2157,2204,2204,2211,2212,2332,2576,...

未达到1000的限制时声明如何:

Select * from tablename where tablename.id in (67,122,173,256,284,285,288,289,291,294,296,298,301,320,346,359,366,425,428,454,528,573,576,584,593,654,654,694,722,838,1833,1976,1979,1979,2002,2004,2005,2045,2083,2109,2114,2126,2126,2157,2204,2204,2211,2212,2332,2576);

4 个答案:

答案 0 :(得分:1)

这是通过使用公用表表达式(CTE)将ID转换为逻辑表然后像往常一样加入来接近它的另一种方法。可能更容易理解它的方式:

-- Build the list of IDs.
with data(str) as (
    select '67,122,173,256,284,285,288,289,291,294,296,298,301,320,346,359
     ,366,425,428,454,528,573,576,584,593,654,654,694,722,838,1833,1976,1979,1979,2002
     ,2004,2005,2045,2083,2109,2114,2126,2126,2157,2204,2204,2211,2212,2332,2576' 
    from dual
),
-- Turn the list into a table using the comma as the delimiter. Think of it
-- like a temp table in memory.
id_list(id) as (
  select regexp_substr(str, '(.*?)(,|$)', 1, level, NULL, 1)
  from data
  connect by level <= regexp_count(str, ',') + 1
)
-- Select data from the main table, joining to the id_list "temp" table where
-- the ID matches.
select tablename.*
from tablename, id_list
where tablename.id = id_list.id;

答案 1 :(得分:0)

  • 慢,丑,但工作解决方案:将字符串拆分为ids并使用游标获取行 OR
  • 基于字符串生成动态选择查询:'select * from tbl where id = 1或id = 2或...'并执行它,不会再快但会起作用。

答案 2 :(得分:0)

不得用于生产:

with list as (
    select to_number(regexp_substr('67,122,173,256,284,285,288,289,291,294,296,298,301,320,346,359
     ,366,425,428,454,528,573,576,584,593,654,654,694,722,838,1833,1976,1979,1979,2002
     ,2004,2005,2045,2083,2109,2114,2126,2126,2157,2204,2204,2211,2212,2332,2576'
     , '\d+', 1, level)) id from dual connect by level < 5000
)
select * from tablename where tablename.id in (select id from list where id is not null);

答案 3 :(得分:0)

您可以使用以下内容:

Sqlite DataBase

您需要在... where ',' || id_list || ',' like '%,' || to_char(id) || ',%' 周围添加逗号(否则3854将匹配38),您需要在to_char(id)周围添加逗号,以便第一个和最后一个值匹配({{}周围的逗号仅需要1}},因为您需要id_list周围的逗号。

这假设id_list的数据类型为NUMBER。如果它已经是VARCHAR2或其他一些字符数据类型,则只需要to_char(id)而不是id。 (严格来说,即使id为NUMBER,也不需要to_char(id),但作为最佳做法,我们不应该依赖隐式转化。)

示例:

to_char()