首页 > 解决方案 > 如何从返回的子查询中选择没有值的记录(具有逗号分隔值)?

问题描述

更新SQL FIDDLE 链接https://www.db-fiddle.com/f/9t63on5kYWUNrHqXkThb1P/4

输出应仅提供以下内容(表 1 的第 2 行)

I0016,I0028,I0045,I0056,I0215,I0321,I0361,I0369,I0420

我应该

select column1 from table1 
where <any comma separated value in column1> not in
(select col2 from table2 where col1 = 'e')

首选的解决方案是原生 SQL,没有特定于供应商的。如有必要,spark sql 函数会有所帮助。

注意:我知道这是一个糟糕的设计,但这不是我能控制的。

注意FIDDLE 中的表是使用 MySQL 的默认设置创建的。我不知道这些表是如何在后端创建的。这就是为什么我指定这不应该是特定于供应商的。

标签: sqlapache-spark-sql

解决方案


你应该修复你的数据结构!在单列中存储值列表不是在 SQL 中存储数据的适当方式。您应该使用联结/关联表。

你可以做你想做的事not exists

select t1.column1
from table1 t1
where not exists (select 1
                  from table2 t2
                  where ',' || t1.column || ',' like '%,' || t2.value || ',%'
                 )

SparkSQL 也可能支持find_in_set(),在这种情况下,您可以执行以下操作:

select t1.column1
from table1 t1
where not exists (select 1
                  from table2 t2
                  where find_in_set(t1.column, t2.value) > 0
                 )

是一个 db<>fiddle。


推荐阅读