表1
表2
想要的结果
laravel框架:
$res = $this->model
->leftJoin('tags as t',function ($join) {
$join->whereRaw(\DB::raw('FIND_IN_SET(t.tag_id,articles.tag)'));
})
->leftJoin('users as u', 'u.user_id', 'articles.user_id')
->where('articles.id',$articleId)
->select('articles.*','u.user_name','u.user_picture',\DB::raw('GROUP_CONCAT(t.tag_name)AS tag_names'))
->groupBy('articles.id')
->first();
原sql:
SELECT `articles`.*, `u`.`user_name`, `u`.`user_picture`,
GROUP_CONCAT(t.tag_name)AS tag_names FROM `articles`
LEFT JOIN `tags` AS `t` ON FIND_IN_SET(t.tag_id,articles.tag)
LEFT JOIN `users` AS `u` ON `u`.`user_id` = `articles`.`user_id`
WHERE `articles`.`user_id` = 4
AND `articles`.`id` <> 4
AND `articles`.`created_at` < '2019-04-22 15:40:51'
GROUP BY `articles`.`id` ORDER BY `articles`.`id` DESC LIMIT 11 OFFSET 0
知识点:
MySQL手册中find_in_set函数的语法:
FIND_IN_SET(str,strlist)
str 要查询的字符串
strlist 字段名 参数以”,”分隔 如 (1,2,6,8)
查询字段(strlist)中包含(str)的结果,返回结果为null或记录
假如字符串str在由N个子链组成的字符串列表strlist 中,则返回值的范围在 1 到 N 之间。 一个字符串列表就是一个由一些被 ‘,’ 符号分开的子链组成的字符串。如果第一个参数是一个常数字符串,而第二个是type SET列,则FIND_IN_SET() 函数被优化,使用比特计算。 如果str不在strlist 或strlist 为空字符串,则返回值为 0 。如任意一个参数为NULL,则返回值为 NULL。这个函数在第一个参数包含一个逗号(‘,’)时将无法正常运行。