mysql 逗号格式关联数据的查询 regexp +replace+group_concat

两张表

表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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值