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;
讓我們瞭解您嘗試 – 2013-12-12 01:38:59
完成。我嘗試了很多東西,但沒有得出結論 – user3093547