查询ORDER BY从另一个SELECT返回的行数 [英] Query to ORDER BY the number of rows returned from another SELECT

查看:70
本文介绍了查询ORDER BY从另一个SELECT返回的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力把注意力集中在SQL上,我需要一些帮助来弄清楚如何在PostgreSQL 9.3中执行以下查询.

I'm trying to wrap my head around SQL and I need some help figuring out how to do the following query in PostgreSQL 9.3.

我有一个 users 表和一个 friends 表,该表在多行中列出了用户ID和朋友的用户ID.

I have a users table, and a friends table that lists user IDs and the user IDs of friends in multiple rows.

我想查询用户表,并按用户ID共有的共同朋友的数量进行ORDER BY.

I would like to query the user table, and ORDER BY the number of mutual friends in common to a user ID.

因此,朋友表如下所示:

user_id | friend_user_id
1       | 4
1       | 5
2       | 10
3       | 7

依此类推,因此用户1将4和5列为朋友,用户2将10列为朋友,因此我想按friend_user_id中用户1的最高计数来排序user_id中的结果选择.

And so on, so user 1 lists 4 and 5 as friends, and user 2 lists 10 as a friend, so I want to sort by the highest count of user 1 in friend_user_id for the result of user_id in the select.

推荐答案

Postgres方法:

The Postgres way to do this:

SELECT *
FROM   users u
LEFT   JOIN (
   SELECT user_id, count(*) AS friends
   FROM   friends
   ) f USING (user_id)
ORDER  BY f.friends DESC NULLS LAST, user_id  -- as tiebreaker

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆