【问题标题】:SQL Following and FollowersSQL 追随者和追随者
【发布时间】:2013-03-19 09:23:28
【问题描述】:

好的,我有两张表,一张名为account_members,另一张名为account_follows。我想要一个 Twitter 风格的关注系统,让 account_members 可以互相关注。

Account Follows Table Structure:

id
account_name
followed_name
time

Account Members Table Structure:

id
Account_name
status (Account active or not)

我想我可以通过一个简单的查询来获得所有被关注的帐户:

public function following($account_name)
{
    $sql = "SELECT 

    F.id, F.account_name, F.followed_name, F.time, 
    M.account_name AS session_name, M.status 

    FROM account_follows F
    LEFT JOIN account_members M ON F.account_name = M.account_name

    WHERE F.account_name = :account_name 
    AND M.account_name = :account_name

    ORDER BY id DESC LIMIT 5";
}

这将显示所有正在关注的 account_members($account_name 是通过 url 设置的)

我遇到的问题是允许登录的 account_member 能够关注或取消关注他们关注的朋友的朋友。我通过执行以下操作对已登录的 account_member 进行简单检查,以取消关注其列表中的任何人:

if($_SESSION['account_name'] == $row['account_name'])
{
    echo'<a href="" id="..." class="...">Unfollow</a>';
}

以上工作正常,但我想对已登录的帐户关注者关注者做类似的事情......如果这有意义吗?

所以 Bob 已登录,Bob 查看他的以下列表并点击 mike 并查看谁 mike 正在关注,并且可以从此列表中关注/取消关注 mike 正在关注的人(其中一些 Bob 可能会关注)

感谢任何帮助或指导。

【问题讨论】:

    标签: php mysql sql


    【解决方案1】:

    您的查询将适用于传入的任何成员的帐户名,但查询本身不考虑当前登录的成员的关注,因此您需要将他们的数据加入其中。

    查询返回 url 指定帐户所关注的成员列表。这有点告诉登录用户是否也在关注该成员。使用该位来决定是否需要回显关注或取消关注链接。

    SELECT 
            theirFollows.id, theirFollows.account_name, 
            theirFollows.followed_name, theirFollows.time, 
            M.account_name AS member_name, M.status, 
            case 
                when myFollows.followed_name is null then 0
                else 1
            end as sessionMemberIsFollowing
    FROM    account_members M
            LEFT JOIN account_follows theirFollows
              ON theirFollows.account_name = M.account_name
            LEFT JOIN 
                (
                    select followed_name
                    from account_follows 
                    where account_name = :session_account_name
                ) myFollows
                on myFollows.followed_name = theirFollows.followed_name
    
    WHERE   M.account_name = :account_name
    

    您选择的其中一个列被标记为 session_name,但这有点误导,因为传入的 account_name 来自 url。此外,您只需要其中一个 where 子句,因为那是您要加入的列。

    【讨论】:

    • 嗨@jhinkley 感谢您抽出宝贵的时间来解决这个问题......看看这个我认为会有一个错误......作为'F'。未在 from 或 left 连接中的任何位置设置...这是 myfollows 还是 theirfollows?
    • 嘿,这似乎与编辑工作正常...唯一的问题是只要 $account_name 从 Session_account_name 更改没有返回结果...似乎很奇怪...你知道为什么这可能会发生吗?
    • 你我的朋友是救命稻草...现在看起来工作正常...我花了一整天试图解决这个问题...这是最优雅和最有效的解决方案吗?另外,我以前从未见过“ else end as”的情况,这到底是做什么的?仅供我将来参考...我会将答案标记为正确...干得好,伙计。
    • Case 就像一个 switch 语句。您定义条件 (when) 及其各自的输出 (then)。由于您要加入 myFollows 子查询,因此 myFollows.followed_name 可能为空。案例检查它是否为空(意味着 session_account 没有匹配的记录),然后将其赋值为 0,否则将其设置为 1。如果您的逻辑需要,您可以在案例中拥有多个“何时”条件。
    猜你喜欢
    • 2019-07-03
    • 1970-01-01
    • 2021-06-13
    • 2017-12-08
    • 2021-10-09
    • 2017-12-17
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多