简体   繁体   English

使用多条件 SQL 的左连接

[英]Using left join with multiple conditions SQL

I am trying to make an application that will display every other user that is not the logged in user or that the logged in user does not not follow (like an explore page), but I'm having trouble writing the SQL query.我正在尝试制作一个应用程序,该应用程序将显示不是登录用户或登录用户未关注的所有其他用户(如探索页面),但我在编写 SQL 查询时遇到了问题。

My tables are set up as:我的表设置为:

following(username1, username2)

(meaning username1 follows username2) (意思是 username1 跟在 username2 后面)

and

users(username, fullname, ...)

Right now I am trying to do something like:现在我正在尝试执行以下操作:

SELECT * FROM
users u 
LEFT JOIN following f ON (
  u.username != 'loggedInUser'
  AND f.username1 = 'loggedInUser'
  AND f.username2 = u.username
)

I replace loggedInUser in a Python script.我在 Python 脚本中替换了loggedInUser

Unfortunately, this query is currently returning all of my users, and it should not be.不幸的是,这个查询目前正在返回我的所有用户,它不应该是。 I'm having a lot of issues working though this logic for some reason, does anyone have some insight?由于某种原因,我在处理这个逻辑时遇到了很多问题,有没有人有一些见解?

This will display every other users that are not the logged in user and (not or) that the logged in user does not not follow (them):这将显示不是logged in user和(不是或) logged in user不关注的所有其他用户(他们):

SELECT * 
FROM users u 
WHERE u.username <> 'loggedInUser'
    AND NOT EXISTS (
            SELECT 1
            FROM following f
            WHERE f.username1 = 'loggedInUser'
                AND f.username2 = u.username
        );

Your query could change to an INNER JOIN to get expected result but it may be more complicated with worse performance:您的查询可能会更改为INNER JOIN以获得预期结果,但性能可能会更差:

SELECT DISTINCT u.* 
FROM users u 
INNER JOIN following f 
ON f.username1 <> 'loggedInUser'
    OR f.username2 <> u.username
WHERE u.username <> 'loggedInUser';

If you need to get all the users not followed by the logged in user, just try the below script.如果您需要获取所有未跟随登录用户的用户,请尝试以下脚本。

SELECT * FROM
users u 
where u.username in(select username2 from following where username1!= 'loggedInUser')
and u.username!='loggedInUser'
SELECT * FROM
users u 
LEFT JOIN following f ON u.[insert_primary_key_here]=f.[insert_foreign_key_here] 
WHERE u.username != 'loggedInUser'
AND f.username1 = 'loggedInUser'
AND f.username2 = u.username

Why don't you simply create a new column in users of bit type that will be updated when any user is being logged in .为什么不简单地在位类型的用户中创建一个新列,该列将在任何用户登录时更新。 Then you just have to write a simply query that would be然后你只需要写一个简单的查询

Select * from users where loggedIn=1从 login=1 的用户中选择 *

that will return you all the users data with logged in status这将返回所有具有登录状态的用户数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM