mysql数据库查询中经常会遇到连表查询,不使用groupBy的话经常会返回笛卡尔集,但是使用groupBy的话,对应的多字段会只返回一个值,这时候我们一般使用group_concat(),该字段就会返回所有值处理后的结果。
- CONCAT语法及使用特点:
CONCAT(str1,str2,…)
返回结果为连接参数产生的字符串。如有任何一个参数为NULL ,则返回值为 NULL。可以有一个或多个参数。
例如商品表对应商品图片表:
/images/goods/goods01.jpg,/images/goods/goods02.jpg,/images/goods/goods03.jpg,/images/goods/goods04.jpg
- laravel中使用group_concat()
可以在select方法中使用DB::raw方法,例如:1
2
3User::select('category',DB::raw('group_concat(id,"|",name,"|" ,figure) as sometitle'))
->groupby('category')
->get();