【发布时间】:2013-06-01 15:29:27
【问题描述】:
我的网站上有 2 个表格,一个 users 表格和一个 user_friendships 表格,每个表格的结构都是这样...
用户
id | user_id | credits_bank | credits_offered
用户友谊
id | user_id | user_followed_id
当我的用户登录时,他会看到网站上的其他用户列表 - 其他用户列表是那些存储在 users 表中并且在 credits_bank 表中的值大于该值的用户credits_offered 表。
创建好友时,会话用户id存储在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 表中的任何人都不是朋友...
【问题讨论】:
-
查询试图做什么?
-
只能有一个
where子句,所以模糊不清你的意思。看起来你想要一个and子句,但它应该做什么?没人知道。也许您需要在访问where之前加入另一个表或查询? -
要获得最佳答案,请编辑您的问题并为您的表粘贴 CREATE TABLE 语句和一些 INSERT 语句。
-
感谢@baileys' 我已经更新了我的问题