SQL的四種連接查詢
內連接
inner join 或者 join
外連接
左連接 left join 或者 left outer join
右連接 right join 或者 right outer join
完全外連接 full join 或者 full outer join
先創建數據庫testjoin
create database testjoin;
然后引用此數據庫testjoin
use testjoin;
然后創建person表和card表
create table person(id int,name varchar(20),cardid int);
create table card(id int,name varchar(20));
然后在表中插入數據
insert into card values (1,'飯卡'),(2,'建行卡'),(3,'農行卡'),(4,'工商卡'),(5,'郵政卡');
insert into person values (1,'張三',1); insert into person values (2,'李四',3); insert into person values (3,'王五',6);
+------+--------+
| id | name |
+------+--------+
| 1 | 飯卡 |
| 2 | 建行卡 |
| 3 | 農行卡 |
| 4 | 工商卡 |
| 5 | 郵政卡 |
+------+--------+
5 rows in set (0.00 sec)
+------+------+--------+
| id | name | cardid |
+------+------+--------+
| 1 | 張三 | 1 |
| 2 | 李四 | 3 |
| 3 | 王五 | 6 |
+------+------+--------+
3 rows in set (0.00 sec)
兩張表並沒有設置外鍵
1.inner join 查詢(內連接查詢)
內連接查詢就是兩張表中的數據,通過某個相等的字段進行查詢,查詢出的結果是兩張表都有的數據,即查詢兩張表的交集
mysql> select * from person inner join card on person.cardid=card.id; +------+------+--------+------+--------+ | id | name | cardid | id | name | +------+------+--------+------+--------+ | 1 | 張三 | 1 | 1 | 飯卡 | | 2 | 李四 | 3 | 3 | 農行卡 | +------+------+--------+------+--------+
2.left join 查詢(左外連接)
左外連接會把左面表中的數據全部取出來,而右邊表中的數據,如果有相等的就像是出來,如果沒有就補充NULL
mysql> select * from person left join card on person.cardid=card.id; +------+------+--------+------+--------+ | id | name | cardid | id | name | +------+------+--------+------+--------+ | 1 | 張三 | 1 | 1 | 飯卡 | | 2 | 李四 | 3 | 3 | 農行卡 | | 3 | 王五 | 6 | NULL | NULL | +------+------+--------+------+--------+
3.right join 查詢(右外連接)
右外連接會把右面表中的數據全部取出來,而左邊表中的數據,如果有相等的就像是出來,如果沒有就補充NULL
mysql> select * from person right join card on person.cardid=card.id; +------+------+--------+------+--------+ | id | name | cardid | id | name | +------+------+--------+------+--------+ | 1 | 張三 | 1 | 1 | 飯卡 | | 2 | 李四 | 3 | 3 | 農行卡 | | NULL | NULL | NULL | 2 | 建行卡 | | NULL | NULL | NULL | 4 | 工商卡 | | NULL | NULL | NULL | 5 | 郵政卡 | +------+------+--------+------+--------+
4.mysql 不支持full join
mysql> select * from person full join card on person.cardid=card.id; ERROR 1054 (42S22): Unknown column 'person.cardid' in 'on clause'
mysql要想實現全連接,可以使用左外連接和右外連接的並集union進行連接
mysql> select * from person right join card on person.cardid=card.id union select * from person left join card on person.cardid=card.id; +------+------+--------+------+--------+ | id | name | cardid | id | name | +------+------+--------+------+--------+ | 1 | 張三 | 1 | 1 | 飯卡 | | 2 | 李四 | 3 | 3 | 農行卡 | | NULL | NULL | NULL | 2 | 建行卡 | | NULL | NULL | NULL | 4 | 工商卡 | | NULL | NULL | NULL | 5 | 郵政卡 | | 3 | 王五 | 6 | NULL | NULL | +------+------+--------+------+--------+