我正在尝试实现“添加好友”页面,但我无法确定为用户显示的所有人可以添加的正确SQL是什么。这是我的表格:
用户:
-id
-name
友谊
-id_user
-id_friend
这是这篇文章的同类数据库:friendship database schema
对于一个用户,我希望所有与他不是朋友的用户,没有让他成为朋友并且没有被要求成为他的朋友
编辑: 这是我想要的结果中最接近的,我试过了:
SELECT *
FROM user user
LEFT JOIN friend friend ON user.id=friend.id
WHERE friend.id IS NULL AND friend.id_friend IS NULL
但它只会归还所有没有朋友的人。
提前致谢!
答案 0 :(得分:0)
不是他的朋友
这应该这样做:
SELECT *
FROM users U
WHERE NOT id IN (
SELECT F.id_friend
FROM friendship F
WHERE U.id = F.id_friend
AND F.id_user = 1
)
AND id != 1
或者
SELECT U.*, F.*
FROM users U
LEFT JOIN friendship F
ON U.id = F.id_friend
AND F.id_user = 1
WHERE F.id_user IS NULL
AND U.id != 1
然而,
没有让他成为朋友并且没有被要求与他成为朋友的人
您的架构中没有此信息。
编辑:太早了:/
答案 1 :(得分:0)
sqlFiddle demo根据您在其他相关问题中解释的friendship schema
。
/* --------------get users who are not friends with 'Tim' */
SELECT u2.id,u2.name
FROM users u1,users u2
WHERE NOT EXISTS(SELECT 1
FROM friendship f
WHERE f.id_user = u1.id AND
f.id_friend = u2.id)
AND NOT EXISTS(SELECT 1
FROM friendship f
WHERE f.id_user = u2.id AND
f.id_friend = u1.id)
AND u1.id != u2.id
AND u1.id = 1;
/* ---------------get users who have not asked 'Tim' to be a friend*/
SELECT u2.id,u2.name
FROM users u1,users u2
WHERE NOT EXISTS(SELECT 1
FROM friendship f
WHERE f.id_user = u2.id AND
f.id_friend = u1.id)
AND u1.id != u2.id
AND u1.id = 1;
/* ------------- get users who have not been asked by 'Tim' to be a friend */
SELECT u2.id,u2.name
FROM users u1,users u2
WHERE NOT EXISTS(SELECT 1
FROM friendship f
WHERE f.id_user = u1.id AND
f.id_friend = u2.id)
AND u1.id != u2.id
AND u1.id = 1;
所有三个查询都已设置为根据Tim
和u1.id = 1
搜索数据,只需将最后一个条件更改为您要查找的任何用户ID。
第一个查询可以合并为OR
条件,如下所示
/* get users who are not friends with 'Tim' */
SELECT u2.id,u2.name
FROM users u1,users u2
WHERE NOT EXISTS(SELECT 1
FROM friendship f
WHERE (f.id_user = u1.id AND
f.id_friend = u2.id)
OR(f.id_user = u2.id AND
f.id_friend = u1.id))
AND u1.id != u2.id
AND u1.id = 1;
左连接解决方案sqlFiddle(您必须替换1
的ID与您选择的用户ID的比较,它们在第一个查询中出现3次,在第二和第三个查询)
/* get users who are not friends with 'Tim' */
SELECT u.id,u.name
FROM users u
LEFT JOIN friendship f ON
(u.id=f.id_user AND f.id_friend = 1)
OR(u.id=f.id_friend AND f.id_user = 1)
WHERE
f.id_friend IS NULL
AND u.id != 1;
/* get users who have not asked 'Tim' to be a friend */
SELECT u.id,u.name
FROM users u
LEFT JOIN friendship f ON
(u.id=f.id_user AND f.id_friend = 1)
WHERE
f.id_friend IS NULL
AND u.id != 1;
/* get users who have not been asked by 'Tim' to be a friend */
SELECT u.id,u.name
FROM users u
LEFT JOIN friendship f ON
(u.id=f.id_friend AND f.id_user = 1)
WHERE
f.id_friend IS NULL
AND u.id != 1;