MySQL 之 表的內連和外連

2021-09-25 23:35:59 字數 1334 閱讀 5287

資料庫中表的連線分為內連;

1.內連線

內連線實際上就是利用where子句對兩種表形成的笛卡兒積進行篩選。

語法:

select 字段 from 表1 inner join 表2 on 連線條件 and 其他條件;
eg:顯示smith的名字和部門名稱

用標準的內連線寫法 :

select ename, dname from emp inner join dept on

emp.deptno=dept.deptno and ename='smith';

2.外連線

外連線分為左外連線和右外連線。

2.1左外連線

如果聯合查詢,左側的表完全顯示就說是左外連線。

語法:

select 欄位名  from 表名1 left join 表名2 on 連線條件;
eg:

建兩張表 :

create table stu (id int, name varchar(30)); -- 學生表

insert into stu values(1,'jack'),(2,'tom'),(3,'kity'),(4,'nono');

create table exam (id int, grade int); -- 成績表

insert into exam values(1, 56),(2,76),(11, 8);

當左邊表和右邊表沒有匹配時,也會顯示左邊表的資料 

select * from stu left join exam on stu.id=exam.id;

2.1右外連線

如果聯合查詢,右側的表完全顯示就說是右外連線。

語法:

select 字段 from 表名1 right join 表名2  on  連線條件;
eg:

select * from stu right join exam on stu.id=exam.id;
方法一:

select d.dname, e.* from dept d left join emp e on d.deptno=e.deptno;

方法二:

select d.dname, e.* from emp e right join dept d on d.deptno=e.deptno;

MySQL 表的內連和外連

內連線實際上就是利用 where 子句對兩種表形成的笛卡兒積進行篩選 標準語法 select 字段 from 表1 inner join 表2 on 連線條件 and 其他條件 例如 顯示 ld 的名字和部門名稱 前面練習過的 用標準寫法 select ename,dname from emp in...

MySQL表的內連和外連

內連線實際上就是利用where子句對兩種表形成的笛卡兒積進行篩選,我們前面學習的查詢都是內連線,也是在開發過程中使用的最多的連線查詢。select 字段 from 表1 inner join 表2 on 連線條件 and 其他條件 案例 顯示smith的名字和部門名稱 用前面的寫法 select e...

表的內連與外連 and 表的索引特性

索引特性 內連線 外連線 左外連線 右外連線建立索引 在建立表的時候,直接在欄位名後指定 primary keycreate table table name id int primary key,name varchar 30 在建立表的最後,指定某列或某幾列為主鍵索引create table t...