1. 程式人生 > 其它 >mysql left join 、inner join 、right join區別

mysql left join 、inner join 、right join區別

首先我們建立倆個表:

一個使用者資訊表:

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL COMMENT '姓名',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性別',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

一個使用者資訊擴充套件表--使用者年級表

CREATE TABLE
`class` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL COMMENT '使用者id', `grade` int(11) DEFAULT NULL COMMENT '年級', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

1、left join (左聯接) 返回包括左表中的所有資料和右表中聯結欄位相等的資料

select * from user as
u left join class as c on u.id = c.user_id

結果是:

2、right join (右聯接)返回包括右表中的所有資料和左表中聯結欄位相等的資料

select * from user as u right join class as c on u.id = c.user_id;

返回結果:

3、inner join(內聯接) 只返回連聯接欄位相等的資料結果

select * from user as u inner join class as c on u.id = c.user_id;

返回結果:

4、union 合併倆個sql語句查詢結果(對結果進行了去重)

使用方式是:

select * from tableA
union
select * from tableB

我們以user表進行演示,union同一個表比較好看出來區別

select * from user union select * from user

返回結果:

5、 union all 合併倆個sql語句查詢結果(沒有對sql語句進行去重)

select * from user union all select * from user

返回結果:

總結一下union和union all的區別:

  1、重複性 union 會把整合後的資料進行去重,union all只是簡單的把倆個數據整合在一起,沒有去重

  2、union 會按照欄位的順序進行排序,union all 不會

  從效率上說,UNION ALL 要比UNION快很多,所以,如果可以確認合併的兩個結果集中不包含重複資料且不需要排序時的話,那麼就使用UNION ALL。