0

我的网站上有两张桌子,一张users桌子和一张user_friendships桌子,每张桌子的结构都是这样......

用户

id  |  user_id  |  credits_bank  |  credits_offered

用户友谊

id  |  user_id  |  user_followed_id

当我的用户登录时,他会看到网站上的其他用户列表 - 其他用户列表是那些存储在表中并且在表中比users表中具有更大价值的用户。credits_bankcredits_offered

建立好友关系时,session usersid存储在user_friendships表中,他关注的其他成员的 id 也存储在该user_friendships列下的表中user_followed_id

问题是我现在需要一个查询来返回所有已移动credits_bankcredits_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 表中的任何人都不是朋友...

4

2 回答 2

1

尝试这个:

SELECT u.id, u.user_id, u.credits_bank, u.credits_offered 
FROM users u 
WHERE u.credits_bank>u.credits_offered
    AND u.user_id = [ENTER LOGGED IN USERS ID HERE] 
    AND u.user_id NOT IN (
        SELECT f.user_ol
        FROM user_friendships f 
    )

如果您有任何问题,请告诉我

编辑 最新的 SQL:

SELECT u.id, u.user_id, u.credits_bank, u.credits_offered 
FROM users u 
INNER JOIN user_friendships f 
   ON f.user_followed_id = u.user_id 
       AND u.credits_bank > u.credits_offered 
       AND f.user_id != [CURRENT_USER_ID]
       AND u.user_id != [CURRENT_USER_ID]
于 2013-06-01T16:06:10.353 回答
1

据我所知,你已经很接近了。如果当前用户的用户 id 被称为 SESS_USER_ID,那么这样的东西应该适合你;

SELECT DISTINCT u.*
FROM users u
LEFT JOIN user_friendships uf 
   ON uf.user_followed_id = u.user_id 
  AND uf.user_id = SESS_USER_ID
WHERE u.credits_offered <= credits_bank
  AND uf.user_followed_id IS NULL
  AND u.user_id <> SESS_USER_ID

(请注意 SESS_USER_ID 在查询中使用了两次以使其简单)

一个用于测试的 SQLfiddle

于 2013-06-01T16:14:27.127 回答