匹配逗号分隔的内容

来源:互联网 发布:快手网络直播怎么赚钱 编辑:程序博客网 时间:2024/05/20 06:06

目的

编写SQL语句,匹配字段值中逗号分隔的内容

相关说明

查询值在字段中的四种表现形式
  1. 要查询值的两侧没有逗号(单一值)
  2. 要查询值的两侧有逗号(在中间)
  3. 要查询值的左侧有逗号(在末尾)
  4. 要查询值的右侧有逗号(在开头)

假设

表名为t_example

字段名为name

要查询的值为computer

实现

1.要查询值的两侧没有逗号

name='computer'
2.要查询值的两侧有逗号

INSTR(name, ',computer,') > 0
3.要查询值的左侧有逗号

SUBSTR(name, INSTR(name, ',', -1) + 1)='computer'
注:INSTR函数中的-1参数表示查找字符时,从末尾第一个字符开始向前查找

4.要查询值的右侧有逗号

SUBSTR(name, 1, INSTR(name, ',', 1) - 1)='computer'

5.最终SQL

SELECT *  FROM t_exapmle WHERE name = 'computer'    OR INSTR(name, ',computer,') > 0    OR SUBSTR(name, INSTR(name, ',', -1) + 1) = 'computer'    OR SUBSTR(name, 1, INSTR(name, ',', 1) - 1) = 'computer'

原创粉丝点击