2011-05-22 77 views
1

发现签入我有一个PostgreSQL下表:SQL查询从朋友

Categories | Locations | Checkins  | Users | Friendships 
id   | id   | id   | id  | user_id 
name  | category_id | location_id | gender | friend_id 
icon  | name  | user_id  |  | 

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

  • 多少女性和男性用户一个位置都有
  • 类别名称和图标
  • 地点名称
  • 有几个朋友CHEC ked在一个位置(从给定的用户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,礼服

+0

'从地点',我相信它应该是。此外,'WHITE friendships.user_id = 1 OR friendships.user_id = 1'应该可以是'WHITE friendships.user_id = 1 OR friendships.friend_id = 1'。我有一个问题:如果两个用户是彼此的朋友,那么在'友谊'中会有多少记录,1或2?并且2条记录应该产生1或2个友谊? – 2011-05-22 10:28:37

+0

thx为您的答案(我固定它,它是早上toooo;))。当两个用户是彼此的朋友时,友谊表中只有一条记录,请求友谊的用户存储在'user_id'中,另一个用于'friend_id' – 23tux 2011-05-22 10:31:01

回答

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 
+0

真棒,解决了! ;) – 23tux 2011-05-23 09:15:54

1

distinct在第一线。对于同一字段,您已经有一个group by子句。让我知道这是否有帮助。