mysql查詢某欄位中以逗號分隔的字串的方法

2021-10-06 09:30:07 字數 1098 閱讀 5886

需求:人員表中有人員角色user_type欄位,乙個人可以有多個角色,user_type存的是以逗號分隔的字串,現在要篩選出多個角色的人員資訊

例如:現在篩選出user_type中含1和2的人員列表

方法一:

1、mysql查詢

select

user_name,

user_type

from

user

where

find_in_set('1', user_type)

or find_in_set('2', user_type)

2、程式裡mybatis可以這樣寫

傳參:list 型別 usertypelist:[1,2]

select user_name,user_type 

from user

1=1

0">

find_in_set(#, user_type)

方法二:

1、mysql查詢

select

user_name,

user_type

from

user

where 1=1

and concat(',', user_type, ',') regexp '(,2,)|(,1,)'

(,2,)作為乙個整體查詢,這樣處理是因為regexp不能根據逗號 分隔篩選,會查出來所有帶2的角色,如:21

2、程式裡寫法

傳參:string型別 usertype: 「1,2」

select user_name,user_type 

from user

1=1

and concat(',', user_type, ',') regexp (concat('(,', replace(#,',',',)|(,'), ',)'))

MYSQL查詢某欄位中以逗號分隔的字串的方法

首先我們建立一張帶有逗號分隔的字串。create table test id int 6 not null auto increment,primary key id pname varchar 20 not null,pnum varchar 50 not null 然後插入帶有逗號分隔的測試資料...

MYSQL查詢某欄位中以逗號分隔的字串的方法

首先我們建立一張帶有逗號分隔的字串。create table test id int 6 not null auto increment,primary key id pname varchar 20 not null,pnum varchar 50 not null 然後插入帶有逗號分隔的測試資料...

MYSQL查詢某欄位中以逗號分隔的字串的方法

首先我們建立一張帶有逗號分隔的字串。create table test id int 6 not null auto increment,primary key id pname varchar 20 not null,pnum varchar 50 not null 然後插入帶有逗號分隔的測試資料...