0

用户表:

ID, UserName, Location

跟随表:

ID, User_ID, User_Follow_ID

--User_ID --> ID of user who is following 

--User_Follow_ID --> ID of user being followed

我想获取用户名,位置与“用户”相同的人的位置,我还想知道用户是否在关注他们。我写的让人们在同一位置的查询如下:

String query = @"
    select * 
    from User 
    where Location = (
        select Location 
        from Users 
        where UserName ='abc'
    ) and UserName != 'abc'
";

我还需要修改此查询以连接或包含来自 Follow 表的数据。

我正在使用 PostgreSql DB 并用 C# 编写代码。任何帮助或建议将不胜感激!

4

1 回答 1

1

您可以使用 ainner join在同一位置查找其他用户,并使用 aleft join检索下表中的潜在匹配项:

select  you.UserName as You
,       case
        when fme.User_Follow_ID is not null then 'True'
        else 'False'
        end as YouFollowMe
,       case
        when fyou.User_Follow_ID is not null then 'True'
        else 'False'
        end as IFollowYou
from    User me
join    User you
on      you.Location = me.Location
        and you.UserName <> me.UserName
left join
        Following fme
on      fme.User_Follow_ID = me.User_ID
        and fme.User_ID = you.User_ID
left join
        Following fyou
on      fyou.User_Follow_ID = you.User_ID
        and fyou.User_ID = me.User_ID
where   me.UserName = 'abc'
于 2012-12-28T11:48:30.287 回答