【问题标题】:Query to find out following查询以了解以下内容
【发布时间】:2014-03-25 23:30:36
【问题描述】:

我有一个用户表和一个友谊表 用户(ID、电子邮件、姓名) 友谊(id,user_id,friend_id,确认)

id   |  email  |  name
1    | xyz     | abc
2    | yui     | poi
3    | tar     | foo
4    | bar     | baz

如果 id 为 1 的用户向 id 为 2 的用户发送好友请求,那么与 id 为好友的行看起来像

id               |  user_id   |  friend_id  | confirmed
1(generated key) |  1         |  2          | false

现在当用户接受好友请求时

id               |  user_id   |  friend_id  | confirmed
1(generated key) |  1         |  2          | true
2                |  2         |  1          | true

所以我基本上想要做的是找出与当前用户不是朋友的用户,如果用户已经与用户成为朋友或者用户已经发送了好友请求,那么生成的哈希数组不应该包含该值.

所以在上述数据库中,哈希结果数组应该包含 id 为 3 和 4 的用户。

所以基本上在友谊表中 user_id 为好友请求发送者 ID,好友 ID 为接收者 ID

因此,无论 user_id 是 current_user,它都不应该有与该friend_id 对应的用户,反之亦然,如果friend_id 是当前用户,则它不应该显示具有相应 user_id 的用户

我希望问题足够清楚,可以理解

抱歉英语不好

【问题讨论】:

    标签: mysql ruby-on-rails-3 activerecord model


    【解决方案1】:

    试试这个:

    select u.* from users u 
    where u.id not in ( select user_id id from friendship 
                        union 
                        select friend_id from friendship );
    

    如果您还想要当前用户的记录,请添加带有当前用户 ID 的 OR 子句。

    select u.* from users u 
    where u.id = ?
       OR u.id not in ( select user_id id from friendship 
                        union 
                        select friend_id from friendship );
    

    用当前用户id填充参数并执行。

    【讨论】:

    • 这个解决方案看起来非常简单和合乎逻辑,但是在这个地方我可以在哪里只为当前登录的用户检查上述查询?
    • 没有。你不能从这个查询。因为,您需要一个不在友谊用户和朋友 ID 中的用户列表。由于其他用户可能在他们的朋友 id 中有当前用户的 id,因此也将被省略。要获取当前用户的记录,只需在上述解决方案中添加OR 子句即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2021-07-05
    • 2020-12-18
    • 2020-08-20
    相关资源
    最近更新 更多