查询是否已添加好友

时间:2012-12-26 10:18:23

标签: sql sql-server-2008 postgresql select

我有一个friends表,用于存储users表的userid和user_friend_id列。

如果我想阻止添加已由特定用户ID添加的朋友,我应该写什么查询?

UserId UserFriendId
1      12
1      13
1      15
2      14
2      17

3 个答案:

答案 0 :(得分:2)

如果结果(totalCount)的值大于零,则表示两个人已经是朋友。

SELECT COUNT(*) totalCount
FROM    tableName
WHERE   (userID = yourID AND UserFriendID = friendID) OR
        (userID = friendID AND UserFriendID = yourID)

答案 1 :(得分:2)

insert into friends (userId, userFriendId)
select 1, 12
where not exists (
    select 1 from friends where userId = 1 and userFriendId = 12
)

答案 2 :(得分:1)

只需创建包含3个参数的存储过程,如下所示:

CREATE PROCEDURE AddUserFriends
@UserID int,
@FriendID int,
@ExcludeUserID int -- the userid you want to exclude adding his friends
AS
BEGIN
INSERT INTO UserFriends(UserID, FriendID)
SELECT @UserID, @FriendID
WHERE @FriendID NOT IN(SELECT FriendID FROM UserFriends WHERE UserID=@ExcludeUserID)
END