mysql常用函数小结

来源:互联网 发布:零售超市收银软件 编辑:程序博客网 时间:2024/04/30 16:45
mysql处理字符串的常用函数:substring_index,concat

1、substring_index(str,delim,count)

        str:要处理的字符串

        delim:分隔符

        count:计数

  例子:str=www.google.com

  substring_index(str,'.',1)

  结果是:www

  substring_index(str,'.',2)

  结果是:www.google

  也就是说,如果count是正数,那么就是从左往右数,第N个分隔符的左边的全部内容

  相反,如果是负数,那么就是从右边开始数,第N个分隔符右边的所有内容,如:

  substring_index(str,'.',-2)

  结果为:google.com

  有人会为,如果我呀中间的的google怎么办?

  很简单的,两个方向:

  从右数第二个分隔符的右边全部,再从左数的第一个分隔符的左边:

  substring_index(substring_index(str,'.',-2),‘.’,1);


2,concat是连接几个字符串。

  concat('wo','lin','xue','bin')

  结果就是wolinxuebin。


3, group_concat(),手册上说明:该函数返回带有来自一个组的连接的非NULL值的字符串结果。

语句 SELECT locus,GROUP_CONCAT(id) FROM info WHERE locus IN('AB086827','AF040764') GROUP BY locus; 的返回结果为
+----------+------------------+
| locus    | GROUP_CONCAT(id) |
+----------+------------------+
| AB086827 | 1,2              |
| AF040764 | 23,24            |
+----------+------------------+

语句 SELECT locus,GROUP_CONCAT(distinct id ORDER BY id DESC SEPARATOR '_') FROM info WHERE locus IN('AB086827','AF040764') GROUP BY locus;的返回结果为
+----------+----------------------------------------------------------+
| locus    | GROUP_CONCAT(distinct id ORDER BY id DESC SEPARATOR '_') |
+----------+----------------------------------------------------------+
| AB086827 | 2_1                                                      |
| AF040764 | 24_23                                                    |
+----------+----------------------------------------------------------+

语句SELECT locus,GROUP_CONCAT(concat_ws(', ',id,journal) ORDER BY id DESC SEPARATOR '. ') FROM info WHERE locus IN('AB086827','AF040764') GROUP BY locus;的返回结果为
+----------+--------------------------------------------------------------------------+
| locus    | GROUP_CONCAT(concat_ws(', ',id,journal) ORDER BY id DESC SEPARATOR '. ') |
+----------+--------------------------------------------------------------------------+
| AB086827 | 2, Submitted (20-JUN-2002). 1, Unpublished                               |
| AF040764 | 24, Submitted (31-DEC-1997) . 23, Unpublished                            |
+----------+--------------------------------------------------------------------------+


0 0
原创粉丝点击