SELECT查询在结果中返回自己的用户名

时间:2016-06-28 18:04:31

标签: c# mysql sql sql-server datagridview

我正在创建一个聊天应用程序,它在加载时查询SQL表,以在datagridview中显示用户当前朋友的列表。我遇到的问题是当前用户也出现在好友列表中。

表的布局是:

create table Friendships
(
FriendshipID int IDENTITY(100,1) Primary Key,
ReceiverID int,
SenderID int,
Approved bit,
)

当有人发送请求时,会在表格中创建一行,其ID为senderID,并且他们将其作为ReceiverID发送给他人,如果有人向该人发送了朋友请求,则表示相反,并且“已批准”设置为0,直到接收方接受好友请求。为了填充datagridview,我需要查询表并返回当前用户是发送者或接收者的所有记录,并显示他们是谁的朋友。每个关系只需要显示一次。

我尝试过的一个问题是:

SELECT UserID, Username, Status 
FROM Arwen_Friendships, Arwen_Users 
WHERE ReceiverID = UserID 
OR SenderID = UserID 
AND ReceiverID = @Current_User_ID 
OR SenderID = @Current_User_ID 
AND Approved =1

其中@Current_User_ID使用当前登录用户的ID进行参数化。我已经尝试了所有方式的连接,SELECT DISTINCT和子查询没有运气。上述查询的结果返回两行:一行包含登录用户的信息,另一行包含ID为发送者或接收者的人,并完全忽略“Approved = 1”。它将返回“Approved = 0”的行。

4 个答案:

答案 0 :(得分:1)

使用全部联盟

(SELECT U.UserID, 
        U.Username, 
        U.Status 
   FROM Arwen_Friendships AF INNER JOIN 
        Arwen_Users U ON AF.SenderID = U.UserID 
  WHERE AF.ReceiverID = @Current_User_ID AND 
        AF.Approved = 1)

  UNION ALL 

(SELECT U.UserID, 
        U.Username, 
        U.Status 
   FROM Arwen_Friendships AF INNER JOIN 
        Arwen_Users U ON AF.ReceiverID = U.UserID 
  WHERE AF.SenderID = @Current_User_ID AND 
        AF.Approved = 1)

答案 1 :(得分:1)

请注意你如何构建你和/或

SELECT UserID, Username, Status 
FROM Arwen_Friendships, Arwen_Users 
WHERE ReceiverID = UserID 
  OR  (SenderID = UserID  AND ReceiverID = @Current_User_ID )
  OR  (SenderID = @Current_User_ID  AND Approved =1)

答案 2 :(得分:0)

试试这个。

SELECT UserID, Username, Status 
from Arwen_Friendships, Arwen_Users 
WHERE (ReceiverID = UserID OR SenderID = UserID ) 
  OR  (ReceiverID = @Current_User_ID OR SenderID = @Current_User_ID) 
  AND (Approved = 1)

答案 3 :(得分:0)

没有paren所有的和首先处理 您可以获得Approved = 0,因为Or是最后一次

SELECT UserID, Username, Status 
FROM Arwen_Friendships, Arwen_Users 
WHERE ( ReceiverID = UserID OR SenderID = UserID ) 
  AND ( ReceiverID = @Current_User_ID OR SenderID = @Current_User_ID ) 
  AND Approved =1