简体   繁体   English

MySQL-按一列进行限制,然后按另一列进行限制

[英]MySQL - Order by one column for a limit then by another column for a limit

I'm developing an application that displays rows which have columns "Time created" and "Number of Likes". 我正在开发一个显示行的应用程序,该行具有“创建时间”和“喜欢的次数”列。

I'm trying to return the first 5 results of my query with the rows that have the most likes, and then the remaining 95 by most recent date, without duplication. 我正在尝试返回查询的前5个结果,其中包含最喜欢的行,然后在最近的日期返回其余的95个,而不重复。

My current query only accomplishes ordering by date. 我当前的查询仅按日期完成排序。

"SELECT * FROM `$category` ORDER BY time DESC LIMIT 100"

Is what I'm attempting to do possible in one query? 我要在一个查询中尝试做的事情吗? Or will I have to perform two queries and filter out duplicate rows? 还是我必须执行两个查询并过滤出重复的行?

UNION automatically removes duplicate rows and LIMIT outside the parethesis applies to the whole query. UNION自动删除重复的行和LIMIT外parethesis适用于整个查询。

(SELECT *, like_count AS likes FROM category ORDER BY like_count DESC LIMIT 5)
UNION
(SELECT *, 0 AS likes FROM category ORDER BY time DESC)
ORDER BY likes DESC, time DESC
LIMIT 100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM