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:406 */
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.'\5 ->select()->toArray();
这种⽅法就是避免了数据的重新遍历,直接在查数据的时候就把域名拼接上,所以性能应该就会好点(具体没测,个⼈认为)
可能举例有点复杂,下⾯是concat()函数的具体⽤法:mysql concat(str1,str2,…) ,可以拼接多个函数
1 SELECT CONCAT('hello',',word!') str;结果为:'hello,word!'
值得注意的是:如果存在参数为null,则结果直接为null
因篇幅问题不能全部显示,请点此查看更多更全内容