WHERE查询在AND语句中?PHP / PDO / MySQL


WHERE query inside an AND statement? PHP/PDO/MySQL

我的网站上有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_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
结果

如果session 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_friendship表中的任何人的朋友。

就我所知,你很接近了。如果当前用户的用户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在查询中使用了两次,以使其简单)

试试这个:

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]