MySQL根据带分隔符的子字符串选择具有LIKE或REGEX的列字符串

时间:2015-12-11 06:59:26

标签: mysql sql regex mysqli

我必须将列值与用户输入数字进行比较。列中的字符串格式为8|5|12|7|

现在,我需要将用户输入值253与此列值进行比较

当我使用LIKE运算符作为'%2|%'时,我通过匹配列值|12|来获得输出

如何使用Regular Expression或其他任何方式匹配字符串?

4 个答案:

答案 0 :(得分:2)

如果我理解问题是正确的,那么为了确保您获得2|....|2|..|2,您需要添加or条款

where col like '%|2|%' 
or col like '2|%'
or col like '%|2'
or col='2'

答案 1 :(得分:1)

在此示例2

中测试12|8|12|5|12|7|2|12|22的内容与此类似

Regular expression visualization

# (^|\|)2(\||$)
# 
# 
# Match the regex below and capture its match into backreference number 1 «(^|\|)»
#    Match this alternative (attempting the next alternative only if this one fails) «^»
#       Assert position at the beginning of the string «^»
#    Or match this alternative (the entire group fails if this one fails to match) «\|»
#       Match the character “|” literally «\|»
# Match the character “2” literally «2»
# Match the regex below and capture its match into backreference number 2 «(\||$)»
#    Match this alternative (attempting the next alternative only if this one fails) «\|»
#       Match the character “|” literally «\|»
#    Or match this alternative (the entire group fails if this one fails to match) «$»
#       Assert position at the end of the string, or before the line break at the end of the string, if any (line feed) «$»

REGEXP "(^|\|)2(\||$)"

这允许列值仅为22|anythinganything|2first thing|2|end thing

答案 2 :(得分:0)

通过查看列设计,您可以做的一种方法是LIKE '%|2|%'

答案 3 :(得分:0)

在单元格中构建“数组”是不好的设计。使用单独的表格。

无论如何,FIND_IN_SET()是一个比正则表达式更容易完成工作的函数。 (但你必须使用',')