![](/img/trans.png)
[英]Not getting results in Hibernate native query using WITH Clause
[英]Using query results as In clause parameter
我知道我以前見過這個,但無法想出搜索詞來找到它。
我有一個 CTE 從下表中返回一個逗號分隔的列表:
Create table Table
(
ID Number
, Name varchar2(100)
);
insert all
into Table (ID, Name) values (1, 'Alex')
into Table (ID, Name) values (2, 'Amy')
into Table (ID, Name) values (3, 'Jim')
select * from dual;
ID | 姓名 |
---|---|
1 | 亞歷克斯 |
2 | 艾米 |
3 | 吉姆 |
select substr(
listagg(Table.ID || ',') within group (order by null)
, 1
, length(listagg(Table.ID || ',') within group (order by null)) - 1
) IDs
from Table
where Name like 'A%'
這給了我結果: 1,2
我正在嘗試在查詢的in
子句中使用此結果:
with CTE as
(
select substr(
listagg(tbl.ID || ',') within group (order by null)
, 1
, length(listagg(tbl.ID || ',') within group (order by null)) - 1
) IDs
from Table
where Name like 'A%'
)
select *
from Table
where cast(ID as varhcar2(1000)) in (select IDs from CTE) --Use results here
--believe the cast is required to compare, otherwise get a ORA-01722: invalid number
我想返回:
ID | 姓名 |
---|---|
1 | 亞歷克斯 |
2 | 艾米 |
如何使用 CTE 生成的IDs
字符串作為in
子句的參數?
恐怕我不明白你的“問題”。 CTE真的很奇怪; SUBSTR 的東西? 為什么? LISTAGG 無論如何都會返回相同的結果。 那你想……什么? 拆分該結果以便您可以在另一個查詢中使用它? 好像你想讓它盡可能復雜(甚至更復雜)來解決“簡單”的問題。 因此:你想解決什么真正的問題?
無論如何,在這里你 go:如果你想在IN
子句中使用它,你必須將聚合字符串拆分成行:
SQL> with CTE as
2 (select listagg(ID || ',') within group (order by null) IDs
3 from Test
4 where Name like 'A%'
5 )
6 select *
7 from Test
8 where id in (select regexp_substr(IDs, '[^,]+', 1, level)
9 from CTE
10 connect by level <= regexp_count(IDS, ',') + 1
11 );
ID NAME
---------- ----------
1 Alex
2 Amy
SQL>
一個簡單的返回相同的結果
SQL> select *
2 from Test
3 where Name like 'A%';
ID NAME
---------- ----------
1 Alex
2 Amy
SQL>
這就是為什么我問:你想解決什么問題?
[編輯]截至尾隨逗號:沒有,至少沒有我使用的任何 Oracle 版本(11g、12c、18cXE、21cXE):
SQL> select listagg(id, ',') within group (order by null) result from test;
RESULT
------------------------------
1,2,3
SQL> select listagg(name, ',') within group (order by null) result from test;
RESULT
------------------------------
Alex,Amy,Jim
SQL>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.