首页 文章

Mysql左外连接,右表中的列不是外键

提问于
浏览
1

我对左外连接的理解是,

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

现在,我想获得公司所在的所有行,而不是上面的结果 . 此外,对于第一个表中的任何条目,如果第二个表中没有相应的条目,那么它应该为第二个表中的所有列提供NULL .

像这样:

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

左外连接可能是上述结果吗?如果没有,我怎样才能得到上述结果?

2 回答

  • 1

    您只需在 LEFT JOINON 部分中添加第二个表(右侧表)的条件即可 .

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

    此外,在多表查询的情况下,建议使用Aliasing,以获得代码清晰度(增强的可读性),并避免明确的行为 .

  • 1

    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'

相关问题