Reputation: 11
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
Upvotes: 0
Views: 59
Reputation: 11
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
Upvotes: 0
Reputation: 44941
select *
from release
where id in
(
select releaseid
from release_favourites
group by releaseid
order by count(*) desc
limit 10
)
order by date
Upvotes: 1
Reputation: 1269773
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.
Upvotes: 0