用于查找好友签到的 SQL 查询
我在 PostgreSQL 中有以下表格:
Categories | Locations | Checkins | Users | Friendships
id | id | id | id | user_id
name | category_id | location_id | gender | friend_id
icon | name | user_id | |
现在,我想检索有关场地的以下信息
- 某个位置有多少女性和男性用户
- 类别名称和图标
- 位置名称
- 有多少朋友在某个位置签到(来自给定用户) id)
除了最后一点,我解决了。但我很难根据给定的用户 ID 来计算好友数量。我用这个查询尝试过:
SELECT distinct locations.id,
max(locations.name) as name,
max(locations.location) as location,
max(categories.name) as cat,
max(categories.icon) as caticon,
SUM(CASE WHEN users.gender = 'm' THEN 1 ELSE 0 END) AS male,
SUM(CASE WHEN users.gender = 'f' THEN 1 ELSE 0 END) AS female,
SUM(CASE WHEN friendships.user_id = 1 OR friendships.friend_id=1 THEN 1 ELSE 0 END) AS friends
FROM locations
INNER JOIN checkins ON checkins.location_id = locations.id
INNER JOIN users ON users.id = checkins.user_id
INNER JOIN categories ON categories.id = locations.category_id
LEFT JOIN friendships ON friendships.user_id = users.id OR friendships.friend_id = users.id
WHERE locations.id=7
GROUP BY locations.id
但是我得到的女性用户计数错误。知道我做错了什么吗?我认为我需要为友谊表添加一个左连接,因为如果用户没有朋友(或没有给出用户),它应该只返回 0 作为朋友计数。
希望我说清楚了, 谢谢,晚礼服
I have the following tables in a PostgreSQL:
Categories | Locations | Checkins | Users | Friendships
id | id | id | id | user_id
name | category_id | location_id | gender | friend_id
icon | name | user_id | |
Now, i want to retrieve the following information about a venue
- How many female and male users a location has
- Category name and icon
- Location name
- How many friends have checked in at a location (from a given user id)
Except the last point, I solved it. But I have troubles to count the friends from a given user id. I tried it with this query:
SELECT distinct locations.id,
max(locations.name) as name,
max(locations.location) as location,
max(categories.name) as cat,
max(categories.icon) as caticon,
SUM(CASE WHEN users.gender = 'm' THEN 1 ELSE 0 END) AS male,
SUM(CASE WHEN users.gender = 'f' THEN 1 ELSE 0 END) AS female,
SUM(CASE WHEN friendships.user_id = 1 OR friendships.friend_id=1 THEN 1 ELSE 0 END) AS friends
FROM locations
INNER JOIN checkins ON checkins.location_id = locations.id
INNER JOIN users ON users.id = checkins.user_id
INNER JOIN categories ON categories.id = locations.category_id
LEFT JOIN friendships ON friendships.user_id = users.id OR friendships.friend_id = users.id
WHERE locations.id=7
GROUP BY locations.id
But I get a wrong number of the count for female users. Any idea what I'm doing wrong? I think I need a left join for the friendships table, because if a user has no friends (or no user is given) it should only return 0 for the friend count.
Hope I made myself clear,
thx, tux
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
distinct
放在第一行中。您已经为同一字段设置了一个group by
子句。让我知道这是否有帮助。Drop the
distinct
in the first line. You already have agroup by
clause for the same field. Let me know if that helps.