Select MariaDB-通过更多选择订购

Select MariaDB-通过更多选择订购,select,tags,mariadb,Select,Tags,Mariadb,我有一个SQL: select * from `posts` where `posts`.`deleted_at` is null and `expire_at` >= '2017-03-26 21:23:42.000000' and ( select count(distinct tags.id) from `tags` inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` where `post_tag`.`po

我有一个SQL:

select * from `posts` 
where `posts`.`deleted_at` is null 
and `expire_at` >= '2017-03-26 21:23:42.000000' 
and (
select count(distinct tags.id) from `tags` 
inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` 
where `post_tag`.`post_id` = `posts`.`id` 
and (`tags`.`tag` like 'PHP' or `tags`.`tag` like 'pop' or `tags`.`tag` like 'UI')
) >= 1
是否可以按帖子中标签的数量对结果进行排序? 也许加上别名


任何信息都可以帮助我。

将相关子查询转换为联接:

select p.*
from posts p
join (
    select pt.post_id,
        count(distinct t.id) as tag_count
    from tags t
    inner join post_tag pt on t.id = pt.tag_id
    where t.tag in ('PHP', 'pop', 'UI')
    group by pt.post_id
    ) pt on p.id = pt.post_id
where p.deleted_at is null
    and p.expire_at >= '2017-03-26 21:23:42.000000'
order by pt.tag_count desc;
另外,请注意,我在中将像和或这样的
串更改为single
,因为您没有匹配任何模式,即字符串中没有
%
。因此,最好在
中使用单个


此外,如果您已经定义了表名、列名等,并且记住了关键字等,那么就不需要使用反勾号。他们使阅读问题变得困难。

我喜欢拉威尔,因为拉威尔。代码是:
$this->posts($request)->where has('tags',function($q)use($tags){$q->where(function($q)use($tags){$foreach($tags as$tag){$q->orWhere('tags.tag','like',$tag[“tag”];}})->选择(DB::raw('count distinct tags.id);})->分页(perPage())@Maximi-对不起?我不明白你的意思。拉威尔有整个SQL的查询生成器。我认为您的SQL不能由Laravel构建。但答案当然是好的。但现在我还没有真正的解决办法。@Maximi-我不是拉威尔的专家。你可以试着把它翻译成拉威尔。如果您不能,请打开一个新问题,发布您当前的sql和laravel尝试是什么。