详解mysql数据库的左连接、右连接、内连接的区别

时间:2023-03-10 01:12:38
详解mysql数据库的左连接、右连接、内连接的区别
一般所说的左连接,外连接是指左外连接,右外连接。做个简单的测试你看吧。
先说左外连接和右外连接:
SQL>select * from t1; ID NAME
---------- --------------------
1 aaa
2 bbb SQL>select * from t2; ID AGE
---------- ----------
1 20
3 30
左外连接:
SQL>select * from t1 left join t2 on t1.id=t2.id; ID NAME ID AGE
---------- -------------------- ---------- ----------
1 aaa 1 20
2 bbb
右外连接:
SQL>select * from t1 right join t2 on t1.id=t2.id; ID NAME ID AGE
---------- -------------------- ---------- ----------
1 aaa 1 20
3 30 从上面的显示你可以看出:左外连接是以左边的表为基准。通俗的讲,先将左边的表全部显示出来,然后右边的表id与左边表id相同的记录就“拼接”上去,比如说id为1的记录。如果没有匹配的id,比如说t1中id为2的t2中就没有。那边就以null显示。
右外连接过程正好相反。 再看内连接:
SQL>select * from t1 inner join t2 on t1.id=t2.id; ID NAME ID AGE
---------- -------------------- ---------- ----------
1 aaa 1 20

看到没有? 只有一条记录。内连接就是只取出符合过滤条件的记录 也就是t1.id=t2.id 那么符合t1.id=t2.id的记录只有id=1这一条,所以只显示一条。 不像外连接,是将你作为基准的表(左外连接就是左边表为基准,右外连接就是右边表为基准)的所有行都显示出来。

转载地址:https://zhidao.baidu.com/question/354682777.html?from=commentSubmit#answers897711300