简体   繁体   English

左外部联接具有多个条件-MYSQL

[英]Left outer join with multiple conditions - MYSQL

I'm running into some problems with a very simple query. 我通过一个非常简单的查询遇到了一些问题。 I figure that it must be because of an incorrect assumption about how SQL queries work. 我认为这一定是由于对SQL查询如何工作的错误假设。 I'm trying to write a simple LEFT OUTER JOIN query using the following tables: 我正在尝试使用下表编写一个简单的LEFT OUTER JOIN查询:

tmtrip_viewer( tmtrip_id, tmuser_id )      -> FKs: (tmtrip.id, tmuser.id)
Values: ( 6, 2 )
        ( 6, 3 )
        ( 7, 4 )

tmtrip( id, ...)
Values: (1, ...)
        (2, ...)
        (3, ...)
        (4, ...)

tmuser(id, username, ...)
Values: (1, user1)
        (2, user2)
        (3, user3)
        (4, user4)

What I want to do is: Display alls id from tmuser table given the following conditions: - That the id != '1' - That the id is NOT in table tmtrip_viewer where tmtrip_viewer.tmtrip_id = 7. 我想做的是:在给定以下条件的情况下,显示tmuser表中的tmuser id :-id!=' tmtrip_viewer该id tmtrip_viewertmtrip_viewer ,其中tmtrip_viewer.tmtrip_id = 7。

Basically, I want to get all the users that are not viewing the tmtrip with tmtrip_id = 7 (except the logged in user ..id='1'). 基本上,我想让所有未使用tmtrip_id = 7查看tmtrip的用户(登录用户..id ='1'除外)。

I have formulated the following query, but it does not behave as desired: 我已经制定了以下查询,但是它的行为不理想:

SELECT a.`id`, a.`username` FROM 
`tmuser` a LEFT OUTER JOIN `tmtrip_viewer` b
ON a.`id` = b.`tmuser_id` AND b.`tmtrip_id` = '7'
WHERE a.id <> '1'

Why is this not working? 为什么这不起作用? What would be the right way to do this? 正确的方法是什么?

Add AND b.tmtrip_id IS NULL to your WHERE . AND b.tmtrip_id IS NULL添加到您的WHERE Your query is getting all tmusers and their "trip 7" info if they have any; 您的查询是获取所有琴手及其“ trip 7”信息(如果有的话); this will reduce the results to only the ones that had no "trip 7" info. 这样会将结果减少到只有没有“ trip 7”信息的结果。

I think this should do what you want. 我认为这应该做您想要的。

It would show one record for each user that doesn't have ID = 1 and also doesn't have a record in tm_tripviewer with tmtrip_id = 7. 它会为每个没有ID = 1的用户显示一条记录,并且在tm_tripviewer中也没有tmtrip_id = 7的记录。

SELECT id, username
FROM tmuser
WHERE id != 1
AND id NOT IN
(SELECT id FROM tmtrip_viewer WHERE tmtrip_id = 7)

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

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