首页 > 解决方案 > 如何在 SQL 中查询多个具有位置的子字符串?

问题描述

我有以下查询:

select position( '/s/' in col)
from table

这行得通。

现在,我希望能够找到/s/or /d/or的位置/c/

我试过:

select position( '[/s/][/c/][/d/]' in col)
from table

但它返回一个错误的值。

例子:

select position( '/s/' in '/s/')

返回 1。

select position( '[/s/][/d/][/c/]' in '/s/')

返回 0

我该如何解决这个问题?

编辑:

简而言之 - 我正在寻找第一次出现的/s/ or /d/ or /c/不要担心边缘情况。

标签: sqlpresto

解决方案


这可能会奏效:

SELECT MAX(patlist.pattern) FROM (VALUES (POSITION('/s/' IN col)), (POSITION('/d/' IN col)), (POSITION('/c/' IN col))) AS patlist(pattern)

包装在查询中:

SELECT (SELECT MAX(patlist.pattern) FROM (VALUES (POSITION('/s/' IN col)), (POSITION('/d/' IN col)), (POSITION('/c/' IN col))) AS patlist(pattern))
FROM MyTable

免责声明:在没有 prestodb 实例的情况下,我只能在备用数据库引擎上对其进行测试。它可能适用于 prestodb,也可能不适用。


推荐阅读