[英]ORACLE SQL CSV Column comparison
I have a table with CSV values as column. 我有一个表,其中包含CSV值作为列。 I want use that column in where clause to compare subset of CSV is present or not.
我想在where子句中使用该列来比较是否存在CSV子集。 For example Table has values like
例如,表的值如下
1| 'A,B,C,D,E'
Query: 查询:
select id from tab where csv_column contains 'A,C' ; 从其中csv_column包含'A,C'的标签中选择ID;
This query should return 1. 该查询应返回1。
How to achieve this in SQL? 如何在SQL中实现呢?
You can handle this using LIKE
, making sure to search for the three types of pattern for each letter/substring which you intend to match: 您可以使用
LIKE
处理此问题,请确保为要匹配的每个字母/子字符串搜索三种模式:
SELECT id
FROM yourTable
WHERE (csv_column LIKE 'A,%' OR csv_column LIKE '%,A,%' OR csv_column LIKE '%,A')
AND
(csv_column LIKE 'C,%' OR csv_column LIKE '%,C,%' OR csv_column LIKE '%,C')
Note that match for the substring A
means that either A,
, ,A,
or ,A
appears in the CSV column. 需要注意的是匹配的子串
A
意味着要么A,
,A,
或,A
出现在CSV列。
We could also write a structurally similar query using INSTR()
in place of LIKE
, which might even give a peformance boost over using wildcards. 我们还可以使用
INSTR()
代替LIKE
编写结构上类似的查询,甚至可以比使用通配符提高性能。
there's probably something funky you can do with regular expressions but in simple terms... if A and C will always be in that order 您可以使用正则表达式进行一些时髦的操作,但是简单来说...如果A和C始终保持该顺序
csv_column LIKE '%A%C%'
otherwise 除此以外
(csv_column LIKE '%A%' AND csv_column LIKE '%C%' )
If you don't want to edit your search string, this could be a way: 如果您不想编辑搜索字符串,可以采用以下方法:
select *
from yourTable
where csv like '%' || replace('A,C', ',', '%') || '%'
For example: 例如:
with yourTable(id, csv) as (
select 1, 'A,B,C,D,E' from dual union all
select 2, 'A,C,D,E' from dual union all
select 3, 'B,C,D,E' from dual
)
select *
from yourTable
where csv like '%' || replace('A,C', ',', '%') || '%'
gives: 给出:
ID CSV
---------- ---------
1 A,B,C,D,E
2 A,C,D,E
Consider that this will only work if the characters in the search string have the same order of the CSV column; 请注意,这仅在搜索字符串中的字符与CSV列的顺序相同时才有效; for example:
例如:
with yourTable(id, csv) as (
select 1, 'C,A,B' from dual
)
select *
from yourTable
here csv like '%' || replace('A,C', ',', '%') || '%'
will give no results 没有结果
为什么不将值存储为单独的列,然后使用简单的谓词过滤?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.