MySQL內連線 外連線(左連線 右連線)查詢

2021-09-28 01:15:04 字數 2301 閱讀 5045

mysql多表查詢在實際應用中是非常重要的, 現在這裡用兩張表讓你徹底搞懂mysql內連線和外連線查詢。其中comment表中的user_id為user表中的id。

準備工作:

建立使用者資訊user表

create table `user` (

`id` int(11) not null auto_increment,

`name` varchar(10),

`***` char(3),

`age` int(11),

primary key (`id`)

) engine=innodb default charset=utf8;

向user表插入資料

insert into `user`(`name`, `***`, `age`) values ('張三','男',18),('李四','男',22),('小玉','女',18),('靈兒','女',19);
create table `comment` (

`id` int(11) auto_increment,

`user_id` int(11) ,

`content` text,

`time` timestamp,

primary key (`id`)

) engine=innodb default charset=utf8;

向commnet表插入資料

insert into `comment`(`user_id`, `content`) values (1,'好久不見啊~'),(3,'是啊,好久不見了,你,還好嗎.....'),(1,'還好,,,吧,只是再也體會不到和那個「她」在一起時的快樂了,,,'),(3,'是啊,再也體會不到那種快樂了,,,'),(2,'我是誰,我在哪?');

內連線和外連線(左連線、右連線)查詢where查詢:

select name,***,age,content from comment,user where user.id=comment.user_id;
內連線查詢:內連線是通過在查詢中設定連線條件的方式,來移除查詢結果集中某些資料行後的交叉連線。簡單來說,就是利用條件表示式來消除交叉連線的某些資料行 。

內連線:select 《列名1,列名2 …> from 《表名1> inner join 《表名2> [ on子句]

select name,***,age,content from comment inner join user on comment.user_id=user.id;
如果把join中的on換成where也是一樣的,這兩種查詢方法使用 where 子句定義連線條件比較簡單明瞭,而 inner join 語法是 ansi sql 的標準規範,使用 inner join 連線語法能夠確保不會忘記連線條件,而且 where 子句在某些時候會影響查詢的效能。

外連線查詢

mysql 中內連線是在交叉連線的結果集上返回滿足條件的記錄;而外連線先將連線的表分為基表和參考表,再以基表為依據返回滿足和不滿足條件的記錄。

外連線更加注重兩張表之間的關係。按照連線表的順序,可以分為左外連線和右外連線。

左連線:

select name,***,age,content from comment left join user on user_id=user.id;
left join 是left outer join的簡寫,它的全稱是左外連線,是外連線中的一種。左(外)連線,左表(comment)的記錄將會全部表示出來,而右表(user)只會顯示符合搜尋條件的記錄。右表記錄不足的地方均為null。

右連線:

select name,***,age,content from comment right join user on user_id=user.id;
right join 是right outer join的簡寫,它的全稱是右外連線,是外連線中的一種。右(外)連線,右表(user)的記錄將會全部表示出來,而右表(comment)只會顯示符合搜尋條件的記錄。右表記錄不足的地方均為null。

MySQL內連線 左外連線 右外連線 全外連線

連線的優勢是減少了外來鍵的使用。內連線 最常見的等值連線,指連線結果僅包含符合連線條件的行,參與連線的兩個表都應該符合連線條件。inner join或join on condition 首先建立兩個表person和card,內容如下 select from card id cardname 1 ca...

內連線,左外連線,右外連線,全連線

1.內連線我們通常用的連線,表表連線只顯示交集資料 2.外連線分左外連線 table1 left outer join on table2 和右外連線table1 right outer join on table2 和全連線 table1 full outer join on table2 2.1...

SQL 內連線,外連線(左外連線 右外連線)

參考整理筆記 關鍵字 inner join on 語句 select from a table a inner join b table bon a.a id b.b id 執行結果 說明 組合兩個表中的記錄,返回關聯字段相符的記錄,也就是返回兩個表的交集 陰影 部分。關鍵字 left join o...