2012-12-28 60 views
0

用戶表: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

你可以使用一個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' 
+0

謝謝@ Andomar..Sry在我的答覆延遲..去了一段時間,瞭解發生什麼事情..雖然你寫了一個非常明確的方式...但我得到「場」不存在「例外..即使我的USERS表有用戶名字段。 – Namrata

相關問題