sql - 尝试从一个表中检查另一个表中的数据
问题描述
我是 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中选择。非常感谢您的帮助,谢谢。
解决方案
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。
推荐阅读
- azure - 有没有办法将自定义翻译器与语音翻译连接起来?
- c# - 如何将数据库中的“EndDate”与今天的当前日期进行比较?
- html - 行数 Sql 查询
- c# - Xamarin iOS 自定义 ListView
- android - 环境变量 ANDROID HOME 未定义 [Windows 10] [无法在安装文件夹中找到 SDK]
- mobile - Flutter TextFormField如何手动添加onChange属性
- hibernate - 相同属性的休眠 hql 多案例语句
- php - 日期格式为 2019-06-17T9:45:04Z
- c++ - 使用 ifstream 对象设置故障位,可能是什么原因?
- python - 如何解决安装pytorch时出现的错误