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

ttcibm8c  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(273)

我对左外连接的理解是,

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

左外连接是否可能产生上述结果?如果没有,我怎样才能得到上面的结果?

ipakzgxi

ipakzgxi1#

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'

oo7oh9g9

oo7oh9g92#

您只需在 ON 部分 LEFT JOIN .

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

另外,在多表查询的情况下,建议使用别名,以提高代码的清晰度(增强可读性),并避免明确的行为。

相关问题