雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

mysql 函数: find_in_set()、instr()

2024-09-20 2

1. find_in_set() 用于在多个字符串子链中查询字符串


find_in_set(str, strlist)

str: 要查询的字符串

strlist: 字段名或字符串, 多个子链以英文逗号 `分割

返回值: 假如字符串 str 在由 N 个子链组成的字符串列表 strlist 中,则返回值的范围在 1 到 N 之间, 不在 strlist 中则返回 0

以下示例中返回值则为: 3 , 因为字符串 yang 在第三个子链中

select find_in_set('yang', 'liang,chen,yang');

应用场景:

在文章表 article 中有个标签字段 tags,一个文章可以有多个标签

标签 id: 1 html 2 css 3 javascript, tags 以 1,2,3 的格式存储标签,那么我们可以使用 find_in_set 查找出 tags 中有 1 的标签

select * from article where find_in_set(1, `tags`);

2. instr() 用于在字符串中查询子字符串


用于在字符串中查询子字符串, 返回子字符串在字符串中首次出现的位置(下标从 1 开始);如果没有找到,则返回 0

select * from `article` where instr(`tags`, 2);select * from `article` where `tags` like '%2%';
更新于:2小时前
赞一波!

文章评论

全部评论