繁体   English   中英

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

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

我对左外部联接的理解是,

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

如果我愿意的话

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

现在,而不是上面的结果,我想获取company是aab的所有行。 同样,对于第一个表中的任何条目,如果第二个表中没有相应的条目,则它应该为我提供第二个表中所有列的NULL。

像这样:

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

左外部联接可能导致上述结果吗? 如果没有,我如何获得上述结果?

您可以在LEFT JOINON部分中简单地添加第二个表(右侧表)的条件。

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

此外,在多表查询的情况下,建议使用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