用于查找好友签入的SQL查询
我在PostgreSQL中有以下表格:用于查找好友签入的SQL查询,sql,postgresql,Sql,Postgresql,我在PostgreSQL中有以下表格: Categories | Locations | Checkins | Users | Friendships id | id | id | id | user_id name | category_id | location_id | gender | friend_id icon | name | user_id |
Categories | Locations | Checkins | Users | Friendships
id | id | id | id | user_id
name | category_id | location_id | gender | friend_id
icon | name | user_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
但我对女性用户的计数是错误的。知道我做错了什么吗?我想我需要一个用于friendships表的左连接,因为如果用户没有朋友(或者没有用户),那么它应该只返回0作为朋友计数
希望我说清楚,
thx,tux在第一行中删除
distinct
。对于同一字段,您已经有了一个group by
子句。如果有帮助,请告诉我。从各个位置,我相信应该是这样。另外,当friendships.user\u id=1或friendships.user\u id=1时,可能应该是当friendships.user\u id=1或friendships.friends\u id=1时
。我有一个问题:如果两个用户是彼此的朋友,那么在友谊中会有多少记录,1还是2?两张唱片应该产生一个或两个友谊吗?谢谢你的回答(我修正了,现在是凌晨;))。当两个用户是彼此的朋友时,友谊表中正好有一条记录,请求友谊的用户存储在user\u id
中,另一条存储在friend\u id
SELECT
L.id,
L.name,
c.name AS cat,
c.icon AS caticon,
COUNT(CASE u.gender WHEN 'm' THEN 1 END) AS male,
COUNT(CASE u.gender WHEN 'f' THEN 1 END) AS female,
COUNT(f.user_id) AS friends
FROM Locations L
INNER JOIN Categories c ON c.id = L.category_id
INNER JOIN Checkins ch ON ch.location_id = L.id
INNER JOIN Users u ON u.id = ch.user_id
LEFT JOIN Friendships f ON f.user_id = @user_id AND f.friend_id = ch.user_id
OR f.user_id = ch.user_id AND f.friend_id = @user_id
WHERE L.id = @location_id
GROUP BY L.id, L.name, c.name, c.icon