互相访问过的地方的SQL查询
我正在为我的大学开发一个使用 Rails 3/PostgreSQL 的项目,其中有用户、活动和场地。一个用户有很多活动,一个场地有很多活动。活动属于用户和场所,因此具有 user_id 和venue_id。
我需要的是一个 SQL 查询(或者甚至是 Rails 本身的方法?)来查找多个用户之间的共同场所。例如,我有 5 个用户访问过不同的场所。 5位用户仅参观了2个场馆。所以我想找回这2个场地。
我首先检索 5 个用户的所有活动:
SELECT a.user_id as user, a.venue_id as venue
FROM activities AS a
WHERE a.user_id=116 OR a.user_id=227 OR a.user_id=229 OR a.user_id=613 OR a.user_id=879
但现在我需要一种方法来找出共同的场所。 有什么想法吗?
谢谢, 无尾礼服
I'm working on a project for my University with Rails 3/PostgreSQL, where we have Users, Activities and Venues. An user has many activities, and a venue has many activities. An activity belongs to an user and to a venue and has therefore an user_id and a venue_id.
What I need is a SQL query (or even a method from Rails itself?) to find mutual venues between several users. For example, I have 5 users that have visited different venues. And only 2 venues got visited by the 5 users. So I want to retrieve the 2 venues.
I've started by retrieving all activities from the 5 users:
SELECT a.user_id as user, a.venue_id as venue
FROM activities AS a
WHERE a.user_id=116 OR a.user_id=227 OR a.user_id=229 OR a.user_id=613 OR a.user_id=879
But now I need a way to find out the mutual venues.
Any idea?
thx,
tux
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我并不完全熟悉 postgresql 的 sql 语法,但试试这个:
从活动中选择venue_id、COUNT(distinct user_id)
其中 user_id 在 (116,227,229,613,879)
按场地 ID 分组
有 COUNT(不同的 user_id) = 5
编辑
:
您需要将“5”更改为您关心的用户数量(您正在寻找的用户数量)。
我在这样的表结构上测试了它:
输出是:
I'm not entirely familiar with sql syntax for postgresql, but try this:
select venue_id, COUNT(distinct user_id) from activities
Where user_id in (116,227,229,613,879)
group by venue_id
having COUNT(distinct user_id) = 5
EDIT:
You will need to change the '5' to however many users you care about (how many you are looking for).
I tested this on a table structure like so:
The output was:
您必须为搜索提供一些参数。例如,5 个用户可能有 2 个共同场所,但不是 3 个。
如果您想查看这 5 个用户有哪些共同场所,您可以首先这样做:
这将为您带来对于这些用户有多少个用户那个场地。所以你有一定程度的“场地共享”。
但是,如果您只想查看五个用户访问过的场所,则需要在最后添加一行:
您还应该考虑将
WHERE
语句从 更改为
You would have to come up with some parameters for your search. For example, 5 user may have 2 Venues in common, but not 3.
If you want to see what Venues these five users have in common, you can start by doing this:
That would bring you, for those users, how many users have that venue. So you have degrees of "Venue sharing".
But if you want to see ONLY the venues who were visited by the five users, you'd add a line in the end:
You should also consider changing your
WHERE
statement fromto
在 sql 中,它会类似于:
您需要连接表,以便获取所有有过活动且有用户的场所。当您刚刚学习时,如果使用子查询,有时可视化会更简单。至少这就是我为我找到的。
in sql it would be something like:
You need to join up your tables so to get all the venues that have had activities that have had users. When you are just learning it is sometimes simpler to visualize it if you use subqueries. At leasts thats what I found for me.