目录
两张表
表1:user
表2:user_total
通过表2的一条数据查询表1的相关数据
select id,name from user where
id REGEXP (
select replace
(
(select user_ids from user_total where id = 3), ',','|'
)
)
通过表2的多条数据查询表1的相关相数据
select id,name from user where
id REGEXP (
select replace
(
(select group_concat(user_ids) from user_total where id IN (3,4,5)), ',','|'
)
)
通过表1的一条数据查询表2的相关数据
select id,user_ids from user_total where user_ids regexp '(^|,)2(,|$)'
通过表1的多条数据查询 表2中满足 表1中一条数据 的相关数据 (兼容上一条查询)
select id,user_ids from user_total where user_ids regexp '(2|3)'
通过表1的多条数据查询 表2中必须满足 表1中所有数据 的相关数据 (使用断言)
select id,user_ids from user_total where user_ids regexp '((?=.*2)(?=.*3)^.*$)'
regexp函数
模式匹配操作符,说白了就是正则
^ 匹配字符串开头
$ 匹配字符串结尾
. 匹配任意单个字符
[...] 匹配括号间的任意字符
[^...] 匹配方括号未列出的任意字符
p1|p2|p3 交替;匹配任意p1或p2或p3
* 匹配前面的元素的零次或多次
+ 匹配前面的元素的一次或多次
{n} 匹配前面的元素n次
{m,n} 匹配前面的元素m至n次
replace函数
replace(str,search,replace)
将str中出现的全部的search替换为replace
group_concat 方法
group_concat( [连接字段] [order by 排序字段 asc/desc ] , [ 分隔符] )
将 连接字段 根据 排序字段 的排序规则用 分隔符 连接在一起
例: group_concat(name order by id desc , ';')
注: 连接字段和排序是一体的中间无逗号,但是与分隔符之间是需要逗号分隔的
select GROUP_CONCAT(name order by id desc ,';') as names from user