简体   繁体   English

mysql外部连接在哪里

[英]mysql outer join with where

I have a database where users must have a username and on another table have an optional contact_name that is given to them by each user. 我有一个数据库,用户必须有一个用户名,而在另一个表上有一个可选的contact_name,每个用户都给他们提供。

For example: 例如:

user A might call user B 'FOO' 用户A可能将用户B称为“ FOO”

but user C calls user B 'BAR' 但是用户C称用户B为“ BAR”

and user D might not have given user B a contact_name 并且用户D可能没有给用户B一个contact_name

so it should return NULL. 因此它应该返回NULL。

The query below works in getting me all the usernames and contact_names even when NULL which is the desired result. 下面的查询可以使我获得所有用户名和contact_names,即使将其作为NULL也是理想的结果。

SELECT Login.username, PhoneNumber.phone, AddressBook.contact_name FROM Login
LEFT OUTER JOIN PhoneNumber ON Login.id = PhoneNumber.user_id
LEFT OUTER JOIN AddressBook ON PhoneNumber.phone = AddressBook.phone

However, I only want to return WHERE AddressBook.user_id = 67 which will return the usernames and contact_names that User A is associated with. 但是,我只想返回WHERE AddressBook.user_id = 67 ,它将返回与用户A关联的用户名和contact_names。

Currently when I add WHERE AddressBook.user_id = 67 it doesn't return any of the contact_names with NULL values which is expected but I need those rows with NULL and without NULL contact_names. 当前,当我添加WHERE AddressBook.user_id = 67它不会返回任何具有NULL值的contact_names,但这是预期的,但是我需要那些具有NULL且没有NULL contact_names的行。

How do I go about this? 我该怎么办?

Thanks 谢谢

How about adding AddressBook.user_id = 67 to the JOIN : 如何将AddressBook.user_id = 67添加到JOIN

SELECT l.username, p.phone, a.contact_name 
FROM Login l
LEFT OUTER JOIN PhoneNumber p ON l.id = p.user_id
LEFT OUTER JOIN AddressBook a ON p.phone = a.phone AND a.user_id = 67
SELECT Login.username, PhoneNumber.phone, AddressBook.contact_name FROM Login
LEFT OUTER JOIN PhoneNumber ON Login.id = PhoneNumber.user_id
LEFT OUTER JOIN (SELECT contact_name, phone, user_id from AddressBook where user_ID = 67 order by 1,2,3)ON PhoneNumber.phone = AddressBook.phone

I think this would be sufficient. 我认为这足够了。 Make your second left join only return the rows with 67 as user id. 使您的第二个左联接仅返回用户ID为67的行。 but honestly without knowing your relationships, it's hard to tell. 但说实话,在不了解您的人际关系的情况下,这很难说。

Is phone number really the only field you can join on? 电话号码真的是您唯一可以加入的领域吗?

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

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