Postgresql - 需要从2个表中获取数据

时间:2012-12-28 11:44:16

标签: sql database postgresql

用户表:

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#中编写代码。 任何帮助或建议将不胜感激!

1 个答案:

答案 0 :(得分:1)

您可以使用inner join查找同一位置的其他用户,并使用left 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'