首页 > 解决方案 > 尝试从一个表中检查另一个表中的数据

问题描述

我是 SQL 的新手,不知何故找到了一份需要我做 SQL 的工作(不要在你的简历中撒谎)。无论如何,我正在尝试执行一个 SELECT 语句,我想在 tableA 中选择一个 columnA,其中 ColumnA 中的单词存在于另一个 tableB 中,下面是我想要实现的示例。

TableA, ColumnA : {Apple, Ball, Chair, Doll, Egg, Fan, Gun, Hat, Ink, Jug}
TableB, ColumnB : {Chair, Ball, Egg, Ink}

所以我试图提出我想要的陈述如下

SELECT ColumnA FROM TableA
WHERE ColumnA = (SELECT ColumnB FROM TableB)

OR

SELECT ColumnA FROM TableA
WHERE ColumnA LIKE '%' + (SELECT ColumnB FROM TableB) + '%'

当然它不起作用,因为它会返回超过 1 个值。我在这方面还是很陌生,不知道如何使用像 CURSOR 这样的功能。非常感谢帮助。谢谢。

(编辑):所以从答案来看,使用 IN 和 JOIN 都可以解决我需要的问题。非常感谢你。但是,我也想知道我需要使用 LIKE 的情况,假设 columnA 和 columnB 有

ColumnA : {'This apple is red', 'This ball is round', 'This chair is metal'}
ColumnB : {'red', 'round'}

所以我想显示来自 columnA 的数据,其中包含 columnB 中存在的关键字。我在想唯一的方法是结合通配符并从columnB中选择。非常感谢您的帮助,谢谢。

标签: sqlsql-server

解决方案


sql server 2016及更高版本,您可以string_split在这种情况下使用函数。

select * from tableA t1
cross apply string_split(t1.ColumnA, ',') t2
where t2.Value in 
(select t2.value from tableB t1
cross apply string_split(t1.ColumnB, ',') t2)

dbfiddle

对于sql server 2014,我们需要使用带有string函数的递归查询。

with cte as
(
    select
        left(ColumnA, charindex(',', ColumnA + ',') - 1) as col1 ,
        stuff(ColumnA, 1, charindex(',', ColumnA + ','), '') as col2
    from tableA
    union all
    select
        left(col2, charindex(',', col2 + ',') - 1),
        stuff(col2, 1, charindex(',', col2 + ','), '')
    from cte
    where
        col2 !=  ''
), cte2 as 
(
    select
        left(ColumnB, charindex(',', ColumnB + ',') - 1) as col1 ,
        stuff(ColumnB, 1, charindex(',', ColumnB + ','), '') as col2
    from tableB
    union all
    select
        left(col2, charindex(',', col2 + ',') - 1),
        stuff(col2, 1, charindex(',', col2 + ','), '')
    from cte2
    where
        col2 !=  ''

)
select * from cte where rtrim(ltrim(col1)) in (select rtrim(ltrim(col1)) from cte2)
option (maxrecursion 0);

dbfiddle


推荐阅读