请建议如何在不使用类似查询的情况下从列中获取特定字符串。 例子。
- 表名称:通知
- 第 1 列:
notificationid
- 第 2 列:
notification_to_id
示例数据:
notificationid notification_to_id
---------------------------------------
1 25,23
2 15,16,25
如何从 notification_to_id
列中仅获取 25 个字符串?
最佳答案
试试这个
SELECT notificationid,
SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(notification_to_id,','),',',value.v),',',-1) as to_id
FROM notification,(SELECT 1 as v UNION
SELECT 2 UNION
SELECT 3 UNION
SELECT 4 UNION
SELECT 5)value
HAVING to_id = '25'
因此,查询通过使用 SUBSTRING_INDEX
和 value.v
来选择 csv 字段中的每个元素,在本例中,该值可以是 1 到最大 5 之间的任意值 ( 由 SELECT 1
... SELECT 5
的 UNION
给出)。如果 csv 字段中只有 3 个元素,则当 value.v
为 4 或 5 时,它将返回空字符串 ''
。 having
是返回包含 25 作为元素的行。
如果notification_to_id
包含超过5个元素,只需添加更多UNION
,如SELECT 6
等等,直到元素的最大数量该栏。
另一种方法是使用像下面这样的REGEX
(但是你有很多次出现 25 来替换
SELECT notificationid,
'25' as value
FROM notification
WHERE notification_to_id REGEXP '(^25$)|(^25,)|(,25$)|(,25,)'
如果 25 是唯一元素 (^25$),则上述查询将匹配 ^ 标记字符串开头 $ 标记字符串结尾。或者如果 25 是第一项 (^25,) 或者如果 25 是最后一项 (,25$) 或者如果 25 位于中间某个位置 (,25,)
或者,如果您想使用LIKE
,请使用以下内容
SELECT notificationid,
'25' as value
FROM notification
WHERE notification_to_id LIKE '25'
OR notification_to_id LIKE '25,%'
OR notification_to_id LIKE '%,25'
OR notification_to_id LIKE '%,25,%'
关于Mysql 包含字符串来获取列中的特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22396745/