简体   繁体   中英

sql order by and limit by another value

So, I have 2 tables, release and release_favourites.

release structure:

  id    date (timestamp)    other data
  1     1486901083          ...
  2     1486909903          ...
  ....

release_favourites structure:

  id    releaseId    userId
  1     2            5
  2     2            10
  ....

I want to order records by date (not problem as you can see in SQL), but I want only 10 records with most favourites, is that possible?

(SQL below works, but only for ordering by date)

SELECT [some rows]
FROM release AS a, release_favourites AS b
WHERE a.id = b.releaseId
ORDER BY a.date
select      *

from        release

where       id in
            (
                select      releaseid
                from        release_favourites
                group by    releaseid
                order by    count(*) desc
                limit       10
            )

order by    date

From your description, you want GROUP BY . You only show one table (although your query has two). This is a (reasonable) guess on what you want:

select rf.release_id
from release_favourites rf
group by rf.release_id
order by count(*) desc
fetch first 10 rows only;

You can join in whatever fields you actually want from another table (or use in or exists ). Not all databases support the ANSI standard fetch first 10 rows only syntax. But all have some way of limiting the result set to a given number of rows.

SELECT DISTINCT [some rows]
FROM release 
WHERE id IN (
       SELECT releaseId 
       FROM (
              SELECT releaseId
              FROM release_favourite
              GROUP BY releaseId
              ORDER BY count(*) 
              DESC LIMIT 10
       )
       AS tmp
)
ORDER BY date

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