MariaDB - 按更多选择排序
MariaDB - order by with more selects
我有这个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;
此外,请注意,我将 like
和 or
组更改为单个 IN
,因为您没有匹配任何模式,即没有 %
细绳。所以,最好使用单个 IN
来代替。
此外,如果您定义了 table 名称、列名等并牢记关键字等,则无需使用反引号。它们使阅读查询变得困难。
我有这个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;
此外,请注意,我将 like
和 or
组更改为单个 IN
,因为您没有匹配任何模式,即没有 %
细绳。所以,最好使用单个 IN
来代替。
此外,如果您定义了 table 名称、列名等并牢记关键字等,则无需使用反引号。它们使阅读查询变得困难。