简体   繁体   中英

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.

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.

(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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