【问题标题】:Performing a multi value LIKE on the result of a CASE WHEN SQL对 CASE WHEN SQL 的结果执行多值 LIKE
【发布时间】:2019-07-04 17:06:26
【问题描述】:

是否可以对 CASE WHEN 的结果执行多值 LIKE(LIKE "x" OR "y" ..)。

我想要达到的目标:

((CASE WHEN customerName IS NULL THEN "abc" ELSE "def" END) LIKE "a" OR "b" or "d")

我不想做的事情:

((CASE WHEN customerName IS NULL THEN "abc" ELSE "def" END) LIKE "a") 
OR ((CASE WHEN customerName IS NULL THEN "abc" ELSE "def" END) LIKE "b") 
OR ((CASE WHEN customerName IS NULL THEN "abc" ELSE "def" END) LIKE "c")

【问题讨论】:

  • 考虑 CTE 或派生表。

标签: sql postgresql case sql-like


【解决方案1】:

您可以使用~ 运算符来执行类似正则表达式的表达式。 例如,假设您有以下值:

'abc'
'qabc'
'ptestp'
'sometext'
'oneone'

如果您只想选择包含abctest 的那些,您可以执行以下查询:

SELECT * FROM (VALUES ('abc'),
                      ('qabc'),
                      ('ptestp'),
                      ('sometext'),
                      ('oneone'))
example_data(label)
WHERE label ~ 'abc|test';

这只会选择以下值: abc, qabc, ptestp.

请记住,~ 运算符在右侧接受正则表达式,因此您可以使用任何类型的模式(如完全匹配、单词开头匹配、单词结尾匹配等)。

例如以下查询:

SELECT * FROM (VALUES ('abc'),
                      ('abcc'),
                      ('ptestp'),
                      ('sometext'),
                      ('oneone'))
example_data(label)
WHERE label ~ '^abc$|^test$';

将只选择第一行 (abc),因为它要求单词完全匹配。

【讨论】:

  • 你也可以用 ~* 来区分大小写
  • 在这种情况下,example_data 指的是什么?
  • example_data 是我使用 VALUES 语句创建的表的名称。 values 语句(在示例中)创建了一个包含 1 列和 4 行的表('abc'、'abcc'、'ptestp'、'sometext'、'oneone')。我将该表命名为example_data,该表包含的唯一列名为label
  • @Dvorog 我会测试这个方法并给你一些反馈。
  • @Dvorog 嘿,抱歉回复晚了,您的回答非常有帮助,谢谢!
【解决方案2】:

您可以将主查询与子查询连接起来。检查这个:

select customerName from 
(
  select 'fff' customerName union all
  select null
) customer
where exists ( 
  select 1 from
  (
    select 'a' x union all
    select 'b' union all
    select 'd'
  ) i
  where (CASE WHEN customerName IS NULL THEN 'abc' ELSE 'def' END) LIKE i.X || '%'
)
|客户名 | | :----------- | | ff | | |

db小提琴here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2023-03-20
    • 2020-09-22
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多