在我的MySQL数据库中,我正计划在阅读有关此文章之后双向存储友谊。
A->乙 B->一种
如果只以一种方式存储友谊,那么这意味着尚未确认或删除友谊。
我现在唯一想知道的是如何查询这个?
如果我要查询所有用户的朋友。我如何才能获得确认的友谊?我是否可以通过遍历数组来解决未经证实的友谊,或者我可以使用这个查询吗?
这又如何解决这个问题呢?什么是仅获得未经证实的友谊的查询?
修改
使用Laravel进行此操作,查询在模型中进行:
$friendsCollection = $this->where('user_a', '=', $currentUserId)->orWhere('user_b', '=', $currentUserId)->get();
这将为我提供友谊中当前用户为user_a或user_b的所有行。
现在我的问题是如何清除"破坏"连接?只存在两行中的一行?
我刚刚发现,当用户开始有很多朋友时,如何对此进行分页。
答案 0 :(得分:1)
您的表格如下所示:
CREATE TABLE users(
userId int PRIMARY KEY,
username VARCHAR(30) NOT NULL
);
CREATE TABLE friendship(
userId int NOT NULL,
friendId int NOT NULL,
PRIMARY KEY (userId, friendId)
);
插入一些值:
insert into users VALUES (1, 'a');
insert into users VALUES (2, 'b');
insert into users VALUES (3, 'c');
insert into friendship VALUES (1,2);
insert into friendship VALUES (2,1);
insert into friendship VALUES (1,3);
因此,查询双向友谊的查询可能如下所示:
SELECT u1.username, u2.username
FROM friendship f1
LEFT JOIN users u1
ON u1.userId = f1.userId
LEFT JOIN users u2
ON u2.userId = f1.friendId
WHERE EXISTS (SELECT * FROM friendship f2 WHERE f2.userId = f1.friendId)
结果:
username username
------------------
a b
b a
单向(未经证实)友谊的查询可能如下所示:
SELECT u1.username, u2.username
FROM friendship f1
LEFT JOIN users u1
ON u1.userId = f1.userId
LEFT JOIN users u2
ON u2.userId = f1.friendId
WHERE NOT EXISTS (SELECT * FROM friendship f2 WHERE f2.userId = f1.friendId)
结果:
username username
------------------
a c