zoukankan      html  css  js  c++  java
  • 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

    多学、 多记、 多练、
  • 相关阅读:
    9、Spring Boot 2.x 集成 Thymeleaf
    【专题】Spring Boot 2.x 面试题
    8、Spring Boot 2.x 服务器部署
    7、Spring Boot 2.x 集成 Redis
    6、Spring Boot 2.x 集成 MyBatis
    5、Spring Boot 2.x 启动原理解析
    4、Spring Boot 2.x 自动配置原理
    3、Spring Boot 2.x 核心技术
    2、Spring Boot 2.x 快速入门
    centOS下安装JDK1.8.60,glassfish4.1.1以及MySQL
  • 原文地址:https://www.cnblogs.com/cyfblogs/p/9816779.html
Copyright © 2011-2022 走看看