gpt4 book ai didi

用于查找 friend 签到的 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 12:48:08 25 4
gpt4 key购买 nike

我在 PostgreSQL 中有以下表格:

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

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

  • 一个地点有多少女性和男性用户
  • 类别名称和图标
  • 地点名称
  • 有多少 friend 在某个位置签到(来自给定的用户 ID)

除了最后一点,我解决了。但是我很难从给定的用户 ID 中计算出 friend 。我用这个查询试过了:

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 表添加一个左连接,因为如果用户没有 friend (或没有给出用户),它应该只为 friend 数返回 0。

希望我说清楚了,谢谢,晚礼服

最佳答案

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

关于用于查找 friend 签到的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6087140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com