简体   繁体   English

MySQL左外部联接,右表中的列不是外键

[英]Mysql left outer join with a column in right table that is not foreign key

My understanding of left outer join is, 我对左外部联接的理解是,

table1:
id(pk) name(unique_key) address phone

table2:
    new_id(pk) name(foreign key) company work-experience

1st table:
1 a x 123
2 b y 234
3 c z 345

2nd table
1 a aaa 2
2 a aab 3
3 b aab 3

if I will do, 如果我愿意的话

select * from table1 left outer join table2 on table1.name=table2.name,

it will give me
1 a x 123 1 a aaa 2
1 a x 123 2 a aab 3
2 b y 345 3 b aab 3
3 c z 345 NULL NULL NULL NULL

Now instead of above result, I want to get all the rows where company is aab. 现在,而不是上面的结果,我想获取company是aab的所有行。 Also , for any entry in 1st table, if there is no corresponding entry in 2nd table then it should give me NULL for all columns in 2nd table. 同样,对于第一个表中的任何条目,如果第二个表中没有相应的条目,则它应该为我提供第二个表中所有列的NULL。

like this: 像这样:

1 a x 123 aab 3
2 b y 234 aab 3
3 c z 345 NULL NULL

is the above result possible with left outer join ? 左外部联接可能导致上述结果吗? If not, How can I get the above result ? 如果没有,我如何获得上述结果?

You can simply add the conditions for the second table (right-side table), in the ON part of LEFT JOIN . 您可以在LEFT JOINON部分中简单地添加第二个表(右侧表)的条件。

SELECT * FROM table1 AS t1
LEFT OUTER JOIN table2 AS t2
  ON t1.name = t2.name AND 
     t2.company = 'aab'

Also, in case of multi-table queries, it is advisable to use Aliasing , for code clarity (enhanced readability), and avoiding unambiguous behaviour. 此外,在多表查询的情况下,建议使用Aliasing ,以确保代码清晰(增强了可读性),并避免了明确的行为。

select t1.name,t1.address,t1.phoneNo,t2.comapnay,t2.workExperiance from table1 as t1 left outer join table2 as t2 on t1.name=t2.name AND t2.company = 'aab'

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

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