无极限的解决方案
我有一个这样的表(来自LeetCode):
requester_id | Accepter_id | Accept_date |
---|---|---|
1 | 2 | 2016/06/03 |
1 | 3 | 2016/06/08 |
2 | 3 | 2016/06/08 |
3 | 4 | 2016/06/09 |
找到拥有最多朋友的人以及最多的好友数量。
预期输出:
id | num |
---|---|
3 | 3 |
我编写了这个查询来获取答案,它有效:
select a.f as "id", count(a.f) as "num"
from (
select requester_id as f
from requestaccepted
union all
select accepter_id as f
from requestaccepted ) a
group by a.f
order by count(a.f) desc
limit 1;
我并不 100% 相信使用 limit 1
是最好的解决方案。
替代/更好的选择应该是什么?
I have a table like this (from LeetCode):
requester_id | accepter_id | accept_date |
---|---|---|
1 | 2 | 2016/06/03 |
1 | 3 | 2016/06/08 |
2 | 3 | 2016/06/08 |
3 | 4 | 2016/06/09 |
Find the people who have the most friends and the most friends number.
Expected Output:
id | num |
---|---|
3 | 3 |
I wrote this query for the answer and it works:
select a.f as "id", count(a.f) as "num"
from (
select requester_id as f
from requestaccepted
union all
select accepter_id as f
from requestaccepted ) a
group by a.f
order by count(a.f) desc
limit 1;
I am not 100% convinced using limit 1
is the best solution.
What should be an alternative/better option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ORDER BY
之后的LIMIT 1
就可以获得单个获胜者:如果有多个获胜者,您将获得任意选择。您可以添加其他
ORDER BY
表达式来获得确定性选择。LIMIT
/FETCH FIRST
(真的吗?),窗口函数row_number()
是一个(更昂贵!)替代方案:如果您必须避免 所有获胜的 ID,只需添加
WITH TIES
。必须使用标准 SQL 语法FETCH FIRST 1 ROWS
而不是 Postgres 快捷方式LIMIT 1
来添加该子句。无需额外的
ORDER BY
表达式来解决关系。如果您必须避免
LIMIT
/FETCH FIRST
(真的吗?),窗口函数rank()
是一个(更昂贵!)替代方案:db>>小提琴此处 - 带有扩展测试用例以显示平局
请参阅:
LIMIT 1
afterORDER BY
is just fine to get a single winner:You get an arbitrary pick if there are multiple winners. You might add additional
ORDER BY
expressions to get a deterministic pick.If you must avoid
LIMIT
/FETCH FIRST
(really?) the window functionrow_number()
is a (more expensive!) alternative:To get all IDs that tie for the win, just add
WITH TIES
. Must use standard SQL syntaxFETCH FIRST 1 ROWS
instead of the Postgres shortcutLIMIT 1
to add the clause.No additional
ORDER BY
expressions, that would resolve ties.If you must avoid
LIMIT
/FETCH FIRST
(really?) the window functionrank()
is a (more expensive!) alternative:db<>fiddle here - with extended test case to show a tie
See:
由于您只需要数量最多的朋友,因此您可以直接获取接受的 id 的数量,并且最多可以使用。
As you just need friends with highest count, you can directly get count of accepted id, and max of that will work.
另一种有趣的方法是使用
Join Lateral
与Limit
架构并插入语句:
Output:
Output:
db<>fiddle 此处
Another interesting way could be using
Join Lateral
withLimit
Schema and insert statements:
Output:
Output:
db<>fiddle here