我的网站上有两张桌子,一张users
桌子和一张user_friendships
桌子,每张桌子的结构都是这样......
用户
id | user_id | credits_bank | credits_offered
用户友谊
id | user_id | user_followed_id
当我的用户登录时,他会看到网站上的其他用户列表 - 其他用户列表是那些存储在表中并且在表中比users
表中具有更大价值的用户。credits_bank
credits_offered
建立好友关系时,session usersid
存储在user_friendships
表中,他关注的其他成员的 id 也存储在该user_friendships
列下的表中user_followed_id
。
问题是我现在需要一个查询来返回所有已移动credits_bank
的credits_offered
用户以及尚未在user_frienships
与会话用户相同的记录中的表中的用户。
我目前正在使用...
SELECT DISTINCT u.*
FROM users u
LEFT JOIN user_friendships uf ON u.user_id = uf.user_followed_id
WHERE u.user_id <> ?
AND u.credits_offered <= credits_bank
AND uf.user_followed_id IS NULL
更新
我想查看其credits_bank
价值大于的用户列表,credits_offered
并且我只想显示它们是否已经存在于我的user_friendships
表中与会话用户在同一行的记录中。
用户
id | user_id | credits_bank | credits_offered
___________________________________________________
1 123 10 2
2 231 6 3
3 312 6 5
4 213 2 1
用户友谊
id | user_id | user_followed_id
___________________________________________________
1 123 231
2 123 312
结果
如果会话 user_id = 123 那么...
user_id 231 and 312 WOULDN'T show as they are in the user friendships table alongside session user id
user_id 213 WOULD show as they have more credits_bank than credits_offered and arent in friendships table
如果会话 user_id 为 312,那么他将看到所有结果,因为他与 user_friendships 表中的任何人都不是朋友...