如何检查BOTH用户和朋友是否已接受请求,只包含查询的user_id组件?
这是表格;
CREATE TABLE friendships (
user_id int,
friend_id int,
accepted boolean not null default false,
UNIQUE KEY friend (user_id, friend_id),
FOREIGN KEY (user_id) REFERENCES users (id)
ON DELETE CASCADE,
FOREIGN KEY (friend_id) REFERENCES users (id)
ON DELETE CASCADE );
这是我的查询;
'select * from friendships ' +
'join users ' +
'on friendships.user_id = users.id ' +
'where friendships.friend_id = ? AND accepted = true '
这只会检查一种方式而且因此,在退回“朋友”时这仍然有效,即使一位用户尚未接受;
user_id: 1, friend_id: 2, accepted: 1
user_id: 2, friend_id: 1, accepted: 0
(请注意,有一方尚未接受)
我想确保两个人都接受了它,所以我不会意外地将非朋友加载到朋友中 - 所以这一点只能算作一个合适的朋友;
user_id: 1, friend_id: 2, accepted: 1
user_id: 2, friend_id: 1, accepted: 1
(注意两者都被接受)
但我只发送了以下数据;
user_id: 1
解决这个问题的聪明方法是什么?我应该使用返回的结果并重新查询每个朋友,对吗?
答案 0 :(得分:2)
每个友谊都有两行,您必须加入friendship
才能找到相互接受的自由联盟。一种方法是这样的:
SELECT u1.*, u2.*
FROM friendship f1
INNER JOIN friendship f2
ON f1.user_id = f2.friend_id AND f1.accepted = true
AND f2.user_id = f1.friend_id and f2.accepted = true
INNER JOIN users u1 ON u1.id = f1.user_id
INNER JOIN users u2 ON u2.id = f2.user_id
WHERE u1.id = ...