MySQL 长知识函数

本文深入讲解了SQL中的多个实用函数,包括find_in_set用于位置查找,concat与concat_ws实现字符串连接,group_concat进行分组连接,from_unixtime及unix_timestamp处理时间格式转换,exists进行子查询验证,以及case when构建条件表达式。每个函数都配有详细的使用示例,帮助读者快速掌握并应用。

find_in_set: 

      用法: find_in_set(str,strlist); 在strlist中查找str,找到就范围所在的位置, strlist必须是用','分割的字符串
例子 :
select FIND_IN_SET('1','1,312,3'); //返回1
select FIND_IN_SET('3','1,312,3'); //返回3
select FIND_IN_SET('12','1,312,3'); //返回0
其他用法
    指定排序: select * from user order by find_in_set( id, '783, 769, 814, 1577, 1769' ) ;

concat

    用法: concat(str1,str2,str3[,str4....]); 字符串链接操作,如果有任何一个参数为null,则返回值为null。
例子 :
SELECT concat('a','b','c');// 返回abc
SELECT concat('a',null);// 返回null

concat_ws

    用法: concat_ws(separator, str1, str2); 用separator作分割符,链接str1,str2.. 
例子 :
SELECT concat_ws('_','a','b','c');// 返回a_b_c

group_concat

    用法: group_concat(filedname) ; 将group by产生的同一个分组中的值连接起来,返回一个字符串结果。
    语法:group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator '分隔符'] )
    说明:通过使用distinct可以排除重复值;如果希望对结果中的值进行排序,可以使用order by子句;separator是一个字符串值,缺省为一个逗号。
例子 :
    SELECT id,(select group_concat(name) from areas  b where b.code=a.province) FROM user_basic a;

from_unixtime

    作用: 将时间戳转化为时间格式 
    用法: from_unixtime(unix_timestamp,format);  unix_timestamp=>时间戳,format=>时间格式
例子 :
    select from_unixtime(1586347261,'%Y%m%d%H%i%s'); 返回20200408200101

unix_timestemp

    作用: 将时间格式转化为时间戳 (与from_unixtime作用相反)
    用法: unix_timestemp(date);  date=>时间格式形式的字符串
例子 :
    select unix_timestemp('2020-04-08 20:01:01'); //返回1586347261

exists 

    SELECT … FROM table WHERE EXISTS (subquery)
    作用:将主查询的数据,放到子查询中做条件验证,根据验证结果(TRUE 或 FALSE)来决定主查询的数据结果是否得以保留。
例子 :    
    SELECT * FROM article WHERE EXISTS (SELECT * FROM user WHERE article.uid = user.uid)
    参考:https://blog.youkuaiyun.com/xiangwang2016/article/details/88204331 


case when then else end


    作用: 条件表达式
    标准格式:
        case
            when 条件1 then 表达式1
            when 条件2 then 表达式2
            ...
            [else 表达式]
        end
例子:
    SELECT id,(
        CASE
        WHEN age < 18 THEN
            '未成年'
        WHEN age < 60 THEN
            '已成年'
        ELSE
            '老年人'
        END
    ) age FROM user;
    附带视频教程:    https://www.bilibili.com/vageeo/BV1n7411378z?from=search&seid=4618555589499576006

参考:https://baijiahao.baidu.com/s?id=1595349117525189591&wfr=spider&for=pc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值