【问题标题】:DB2 splitting comma separated String to use in a IN clause.. Update: WITH clause query inside IN clauseDB2 拆分逗号分隔字符串以在 IN 子句中使用。更新:IN 子句中的 WITH 子句查询
【发布时间】:2016-05-26 13:57:45
【问题描述】:

我有一个表TableA 的值在ColumnA 中,如下所示:

ColumnA
__________________
a,b,c
d,e

我的表 TableB 的值为:

ColumnB     ColumnC
____________________
a            1
b            2
c            3
d            4
e            5
x            9

我想在另一个查询中使用上述值:

SELECT columnC FROM TableB where ColumnB in (select ColumnA from TableA)

显然上面的查询是行不通的。

输出应该是1、2、3、4、5。

如何在没有函数的情况下执行此操作,即在简单查询中?

更新:

根据以下 mustoccio 的评论,我使用 WITH 子句使其工作:

With split_data as (select ColumnA as split_string, ',' as split from TableA),
rec
(
   split_string, split, row_num, column_value, pos
)
as
(
   select
   split_string,
   split,
   1,
   varchar(substr(split_string, 1, decode(instr(split_string, split, 1),0,length(split_string), instr(split_string, split, 1)-1)), 255),
   instr(split_string, split, 1) + length(split)
   from split_data
   union
   all
   select
   split_string,
   split,
   row_num+1,
   varchar(substr(split_string, pos, decode(instr(split_string, split, pos),0, length(split_string)-pos+1, instr(split_string, split, pos)-pos)), 255),
   instr(split_string, split, pos)+length(split)
   from rec
   where row_num < 300000
   and pos > length(split)
)
select
column_value as data
from rec
order by row_num

但是,当我尝试在查询的 IN 子句中使用上述查询时:

SELECT columnC FROM TableB where ColumnB in (/* WITH query here */)

我得到错误:

Error: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=as;in ( With split_data;JOIN, DRIVER=3.50.152
SQLState:  42601
ErrorCode: -104
Error: DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-104;42601;as|in ( With split_data|JOIN, DRIVER=3.50.152
SQLState:  56098
ErrorCode: -727

我们不能在 IN 子句中使用 WITH 子句查询吗? 如果否,解决办法是什么?

【问题讨论】:

  • 看看这是否有帮助:stackoverflow.com/questions/24367069/…
  • @mustaccio:答案中的链接未在此处打开! :( 可以将代码作为答案发布在下面吗?
  • 您可能需要查看手册中SELECT 的语法图。 CTE 总是在语句的开头:with foo(bar) as (...) select x from y where z in (select bar from foo)

标签: string db2


【解决方案1】:

内连接必须在这里工作..你可以使用这个

select columnC from tableB inner join tableA on tableB.columnB=tableA.columnA;

enter image description here

你可以在这里看到结果

【讨论】:

  • 有人否决了您的答案,因为它不正确。 TableA 与您在答案图像中描述的方式不同。 TableA 有问题中提到的逗号分隔值。
猜你喜欢
  • 2013-06-04
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 2018-02-13
  • 1970-01-01
相关资源
最近更新 更多