用于查找朋友签到的SQL查询

时间:2011-05-22 09:43:22

标签: 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      |        |

现在,我想检索有关场地的以下信息

  • 一个地点有多少女性和男性用户
  • 类别名称和图标
  • 位置名称
  • 有多少朋友在某个位置(来自给定的用户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。

希望我说清楚, thx,tux

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

distinct放在第一行。您已经为同一个字段提供了group by子句。如果有帮助,请告诉我。