• MySQL中CONCAT()的用法


    MySQL中CONCAT()的用法

    在日常开发过程中,特别是在书写接口的时候,经常会遇到字符串拼接的情况,比如在返回图片数据时,数据库里往往存储的是相对路径,而接口里一般是存放绝对地址,这就需要字符串拼接了

    一、通过PHP拼接

    这种方法比较简单,可以通过圆点‘.’实现

    1  //获取商品规格信息2  $sku = Db::name('product_attr')->where(['product_id'=>$id])
    3       ->field('id,attr,attr_id,stock,common_price,super_price,img')
    4       ->select()->toArray();
    5  $sku = set_img_url($sku,'img');
     1 /**
     2  * 功能:批量转换图片地址
     3  *
     4  * User: cyf
     5  * Time: 2018/8/22 0022 18:24
     6  */
     7 function set_img_url($arr = [],$str = 'thumbnail')
     8 {
     9     if(empty($arr)) return $arr;
    10     foreach ($arr as $key=>$val) {
    11         $arr[$key][$str] = get_absolute_img($val[$str]);
    12     }
    13     unset($val);
    14     return $arr;
    15 }
    1 /**
    2  * 功能:将图片由相对地址转为绝对地址
    3  *
    4  * User: cyf
    5  * Time: 2018/8/22 0022 10:40
    6  */
    7 function get_absolute_img($img){
    8     return cmf_get_domain() . $img;
    9 }

    这种方法就是在数据库里取出数据之后,再把数据遍历一遍,在遍历过程中拼接域名,所以性能上就差点了

    二、MySQL拼接

    1、直接通过mysql中的concat()函数进行拼接

    1 //3、规格
    2 $domain = cmf_get_domain();
    3 $sku = Db::name('product_attr')->where(['product_id'=>$id])
    4      ->field('id,attr,attr_id,stock,common_price,super_price,concat("'.$domain.'", img) img')
    5      ->select()->toArray();

    这种方法就是避免了数据的重新遍历,直接在查数据的时候就把域名拼接上,所以性能应该就会好点(具体没测,个人认为)

    可能举例有点复杂,下面是concat()函数的具体用法:

    mysql concat(str1,str2,…) ,可以拼接多个函数

    1 SELECT CONCAT('hello',',word!') str;结果为:'hello,word!'

    值得注意的是:如果存在参数为null,则结果直接为null

    多学、 多记、 多练、
  • 相关阅读:
    软件工程课程作业(四)--返回一个整数数组中最大子数组的和
    构建之法阅读笔记02
    第三周学习进度
    Delphi 之 编辑框控件(TEdit)
    Delphi 之 标签组件(TLabel组件)
    Delphi 之 第九课 Windows编程
    Delphi 之 第八课 动态数组
    VB API 之 第六课 字体应用三
    VB API 之 第五课 字体之其他函数介绍
    Delphi 之 第七课 字符串操作
  • 原文地址:https://www.cnblogs.com/cyfblogs/p/9816779.html
Copyright © 2020-2023  润新知