mysql的常用查询辅助函数汇总

摘要  mysql的find_in_set() instr() replace() substring() crrent_timestamp()的小例子等

在日常开发中我们除了要熟练掌握一些基础的mysql命令外,也需掌握一些比较复杂的查询方式,下面做简单的列举。

1、find_in_set(fieldstrlist)

find_in_set()可以帮助我们方便的查询field字段值集合 strlist 中的的记录

比如:

?
1
select  * form table_name  where  find_in_set(id,  '1,2,3,4,5,6' );


则为查询id值为1,2,3,4,5,6的记录,且会按照 strlist 中的集合顺序返回

即:

?
1
select  * form table_name  where  find_in_set(id,  '1,2,4,6,5,3' );


则会一次返回id值为1,2,4,6,5,3的记录。

mysql会将 strlist 作为一个元素集合处理,理解成[1,2,3,4,5,6,7,8,9,10]就可以了,在其中寻找与field字段相等的元素并返回其所在集合中位置。

这里在举例下instr让大家更明了些:

instr查找的是查找串在主串中第一次与其相匹配的位置,即便你想查找5,但他在50处就与这里的5相匹配了,然后返回其位置,从1开始。

?
1
2
select  instr( '1,2,3,4,50,5' , 5); 
> 9

find_in_set()的匹配组则是一个集合,就像数组一样,查询指定元素是否在此集合里,存在则返回其所在位置下标,从1开始。

?
1
2
select  find_in_set( '5' '1,2,3,4,50,5' );
> 6
2、instr(seastr, target)

instr是用来查询target是否存在与seastr中,若存在则返回其第一次出现的位置,注意是完全匹配,而非like命令里的相似匹配

?
1
2
3
4
5
6
select  instr( 'I am serach string!' 'am' );//exist
> 3
select  instr( 'I am serach string!' 'hello' );// not  exist
> 0
select  instr( 'I am serach string!' 'amount' );
> 0
3、replace(source, target, value)

replace用来在source中查找target并将target替换为新的value,批量更新某字段的通用内容很有效

?
1
update  table_name  set  column_name =  replace (column_name,  'the old value' 'the new value' );
4、substr(source, start, length) 获取一定长度和偏移量的子串
?
1
2
select  substr( 'the source str' , 5, 6);
> source
5、current_timestamp() 当前datetime时间yyyy-mm-dd H:i:s

    做个小例子

?
1
inset  into  table_name  values ( '1' , 'sallency' , current_timestamp );
6、in的使用方法以及sql内部排序处理
?
1
2
3
4
5
6
7
8
//默认按查询字段的升序
select * from table_name where id in ( 1 , 2 , 3 , 4 , 5 , 6 );
//field(col,arg1,arg2,arg3,arg4)指定顺序
select * from table_name where id in ( 1 , 2 , 3 , 4 , 5 , 6 ) order by field(id, 6 , 5 , 4 , 3 , 2 , 1 , 0 );
//find_in_set(col,'arg1,arg2,arg3,arg4')指定顺序
select * from table_name where id in ( 1 , 2 , 3 , 4 , 5 , 6 ) order by find_in_set(id, '6,5,4,3,2,1' );
//按序列顺序
select * from table_name where find_in_set(id, '6,5,4,3,2,1' );
7、left join right join inner join

    我们经常用到关联查询来对两个表做检索,left or right 谁在左边谁是老大, a left join b则以a在左,a为主查询,b可能没有关联的值存在,那就是空,b left join a 则 b 在左,b为主查询。

    inner join比较友好,a b 平定地位,两者都有的才会被关联查询出来,

?
1
2
3
select  table_a.*, table_b.*  from  table_a  left  join  table_b  on  table_a.id = table_b.id
select  table_a.*, table_b.*  from  table_a  right  join  table_b  on  table_b.id = table_a.id
select  table_a.*, table_b.*  from  table_a  inner  join  table_b  on  table_a.id = table_b.id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值