首页 > 解决方案 > 如何检查列中是否仅存在值组合?

问题描述

我有一个值列表,我只想获取该列只有值组合的行:

Ex:
>CREATE TABLE User_Group(
        [id] [int] NOT NULL,
        [names] [varchar](255) NOT NULL,
 ) ON [PRIMARY]

    Sample content User_Group:
    1:" Joe,Jane"
    2:"Jane, James,Frank"
    3: "Jane, Joe,James"

我正在传递一个名称列表,我想检查 User_group 表中是否存在名称组合并返回行。只有当它包含 EXACT 组合时,我才想要这些行。

因此,例如,如果给我 James、Jane 和 Joe,我想检查 2^3-1 次,如果 James、Jane、Joe、James&Jane、James&Joe、Jane&joe、James&Jane&Joe 存在于表中。从这种情况下,我应该只得到第 1 行和第 3 行。第 2 行被跳过,因为它有弗兰克。

我知道我可以存在,但不确定如何仅检查该特定组合。

我也不确定如何“循环”所有组合 - 我考虑过使用 Java 使用不同的组合进行 2^x-1 调用(鉴于这种组合不太可能>15)。

我还阅读了有关“全选”的信息,但不确定这是否仅对不同的组合有帮助。

我怎样才能优雅地做到这一点?

标签: sqlsql-serverdatabase

解决方案


这是一个使用 CTE 来做你想做的事的版本。

我创建了一个表@list,其中包含您提供的列表,以及另一个表@search,其中包含每个搜索词。

declare @list table(k int, l varchar(100))
insert @list values (1,' Joe,Jane')
,(2,'Jane, James,Frank')
,(3,'Jane, Joe,James')

declare @search table(sk int,s varchar(20))
insert @search values (1,'jane'),(2,'joe'),(3,'james')

-- Top level CTE to remove spaces, and each term is surrounded by its own commas.
;with cte as (
    select k,','+replace(replace(l,',',',,'),' ','')+',' l from @list
    )
-- Go through the search terms recursively and remove the search terms, with their surrounding commas
,cte2 as(
    select cte.k, replace(cte.l,','+s+',','') as l, s.sk, s.s 
    from cte
    join @search s on sk=1
    union all
    select cte2.k, replace(cte2.l,','+s.s+',','') as l, s.sk ,s.s
    from cte2
    join @search s on s.sk=cte2.sk+1
)
-- Find any that result in zero length
select distinct k from cte2 where len(l)=0

推荐阅读