[英]sql order by and limit by another value
So, I have 2 tables, release and release_favourites. 所以,我有2个表,release和release_favourites。
release structure: 发布结构:
id date (timestamp) other data
1 1486901083 ...
2 1486909903 ...
....
release_favourites structure: release_favourites结构:
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中是没有问题的),但是我只希望最喜欢的10条记录可以吗?
(SQL below works, but only for ordering by date) (下面的SQL有效,但仅适用于按日期排序)
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
. 根据您的描述,您需要
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
). 您可以在任何领域,你实际上是从另一个表要加入(或使用
in
或exists
)。 Not all databases support the ANSI standard fetch first 10 rows only
syntax. 并非所有数据库都支持ANSI标准
fetch first 10 rows only
语法。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.