当前位置:   article > 正文

mysql 逗号格式关联数据的查询 regexp +replace+group_concat_两表关联支持regexp吗

两表关联支持regexp吗

两张表

表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), ',','|'
	)
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
通过表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
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
通过表1的一条数据查询表2的相关数据
select id,user_ids from user_total where user_ids regexp '(^|,)2(,|$)'
  • 1
通过表1的多条数据查询 表2中满足 表1中一条数据 的相关数据 (兼容上一条查询)
select id,user_ids from user_total where user_ids regexp '(2|3)'
  • 1
通过表1的多条数据查询 表2中必须满足 表1中所有数据 的相关数据 (使用断言)
select id,user_ids from user_total where user_ids regexp '((?=.*2)(?=.*3)^.*$)'
  • 1
regexp函数
模式匹配操作符,说白了就是正则

^  匹配字符串开头

$  匹配字符串结尾

.  匹配任意单个字符

[...]  匹配括号间的任意字符

[^...] 匹配方括号未列出的任意字符

p1|p2|p3  交替;匹配任意p1或p2或p3

*  匹配前面的元素的零次或多次

+ 匹配前面的元素的一次或多次

{n} 匹配前面的元素n次

{m,n} 匹配前面的元素m至n次

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
replace函数
replace(str,search,replace)
将str中出现的全部的search替换为replace
  • 1
  • 2
group_concat 方法
group_concat( [连接字段]  [order by 排序字段  asc/desc  ] , [ 分隔符] )
将 连接字段 根据 排序字段 的排序规则用 分隔符 连接在一起

例: group_concat(name order by id desc , ';')

注: 连接字段和排序是一体的中间无逗号,但是与分隔符之间是需要逗号分隔的

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
select GROUP_CONCAT(name order by id desc ,';') as names from user 
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/230861
推荐阅读
相关标签
  

闽ICP备14008679号