具有1个以上值的单元格的嵌套sql in语句

i5desfxk  于 2021-08-13  发布在  Java
关注(0)|答案(4)|浏览(354)



如何编写sql,以便它返回我 tom,ken,jerry 我尝试了这个sql作为

select name
  from staffDB
 where dept in (select value 
                  from ConfigDB 
                 where key = 'dept')

但是它不返回值,不,不,我不允许修改数据库设计。

eivgtgni

eivgtgni1#

您的数据库设计不是最佳的,因为它存储的是csv值。也就是说,这里有一种方法可以获得您想要使用的输出 LISTAGG (11g+):

SELECT
    c."Key",
    LISTAGG(s.Name, ',') WITHIN GROUP (ORDER BY s.Dept) Departments
FROM ConfigDB c
LEFT JOIN StaffDB s
    ON ',' || c."Value" || ',' LIKE '%,' || s.Dept || '%,'
GROUP BY
    c."Key";

演示

请注意,我们使用以下逻辑将config表中的部门csv列表与staff表中的每个标量值进行比较,例如:

,A,B,C, LIKE '%,A,%'

也就是说,我们在部门的csv字符串上加上逗号,这样我们就可以搜索每个可能的标量部门。

bsxbgnwa

bsxbgnwa2#

一种选择是用逗号分开,然后用 LISTAGG() 内部功能 SELECT .. CONNECT BY level .. 声明:

WITH ConfigDB( key, value ) AS
(
 SELECT 'dept', 'A,B,C' FROM dual
), StaffDB( name, dept ) AS
(
 SELECT 'tom'  , 'A' FROM dual UNION ALL
 SELECT 'ken'  , 'B' FROM dual UNION ALL
 SELECT 'jerry', 'C' FROM dual  
), t AS
(
 SELECT REGEXP_SUBSTR(value,'[^,]',1,level) AS letter, level AS lvl
   FROM ConfigDB
  CONNECT BY level <= REGEXP_COUNT(value,',') + 1
)
SELECT LISTAGG(name,',') WITHIN GROUP (ORDER BY lvl) AS DBNAme
  FROM t  
  JOIN StaffDB
    ON dept = letter

演示

uoifb46i

uoifb46i3#

可以使用层次结构查询拆分值,然后按如下方式将其联接:

SQL>  SELECT
2      C.KEY,
3      LISTAGG(S.NAME, ',') WITHIN GROUP(ORDER BY S.DEPT) DEPARTMENTS
4     FROM
5      CONFIGDB   C
6      CROSS JOIN TABLE ( CAST(MULTISET(
7          SELECT REGEXP_SUBSTR(C.VALUE, '[^,]+', 1, LEVEL)
8            FROM DUAL
9          CONNECT BY LEVEL <= REGEXP_COUNT(C.VALUE, '[^,]+')
10      ) AS SYS.ODCIVARCHAR2LIST) ) C1
11      LEFT JOIN STAFFDB    S ON S.DEPT = C1.COLUMN_VALUE
12    GROUP BY C.KEY;

KEY   DEPARTMENTS
----- ---------------
dept  tom,ken,jerry

SQL>
rkttyhzu

rkttyhzu4#

请使用下面的查询,

select * from 
(select LISTAGG(Name, ',') WITHIN GROUP (ORDER BY Dept) as name, 
LISTAGG(Dept, ',') WITHIN GROUP (ORDER BY Dept) as dept from staffDB)
where dept  in
(select value from ConfigDB);

下面是测试用例,

相关问题