我有一个存储 users 表的用户 ID 和 user_friend_id 列的朋友表。
如果我想阻止添加已经由特定用户 ID 添加的朋友,我应该写什么查询?
UserId UserFriendId
1 12
1 13
1 15
2 14
2 17
我有一个存储 users 表的用户 ID 和 user_friend_id 列的朋友表。
如果我想阻止添加已经由特定用户 ID 添加的朋友,我应该写什么查询?
UserId UserFriendId
1 12
1 13
1 15
2 14
2 17
如果结果 ( totalCount
) 的值大于零,则表示两个人已经是朋友。
SELECT COUNT(*) totalCount
FROM tableName
WHERE (userID = yourID AND UserFriendID = friendID) OR
(userID = friendID AND UserFriendID = yourID)
insert into friends (userId, userFriendId)
select 1, 12
where not exists (
select 1 from friends where userId = 1 and userFriendId = 12
)
只需创建具有 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