Home > Database > Mysql Tutorial > 章节2:SQL之多表连接_MySQL

章节2:SQL之多表连接_MySQL

WBOY
Release: 2016-06-01 13:18:29
Original
1075 people have browsed it

bitsCN.com

Sql的多表连接关系有:内连接、外连接和交叉连接。

先建立两个用于演示的表:

TB_Characters:

Id Character
1 内向
2 外向
3 中性性格

TB_Colors:

Id Color
1 绿色
2 红色
4 蓝色

一、内连接:

内连接(JOIN  或 INNER JOIN):内连接取交集

示意图:

image

SELECT * FROM tb_characters INNER JOIN tb_colors ON tb_characters.ID = tb_colors.ID;
Copy after login

结果:

image

二、外连接:

外连接可分为:左连接、右连接、完全外连接。

1、左连接(LEFT JOIN):

示意图:

image

SELECT * FROM tb_characters LEFT JOIN tb_colors ON tb_characters.ID = tb_colors.ID;
Copy after login

结果:

image

2、右连接(RIGHT JOIN):

示意图:

image

SELECT * FROM tb_characters RIGHT JOIN tb_colors ON tb_characters.ID = tb_colors.ID;
Copy after login

结果:

image

3、完全外连接:

示意图:

image

select * from tb_characters LEFT JOIN tb_colors on tb_characters.ID=tb_colors.IDUNIONselect * from tb_characters RIGHT JOIN tb_colors on tb_characters.ID=tb_colors.ID
Copy after login

结果:

image

三、交叉连接( CROSS JOIN ):

交叉连接产生连接所涉及的表的笛卡尔积。

SELECT * FROM tb_characters CROSS JOIN tb_colors;
Copy after login

结果:

image


补充:

1、如下可获取内连接结果:

SELECT * FROM tb_characters,tb_colors WHERE tb_characters.ID = tb_colors.ID;
Copy after login

2、如下可获取交叉连接结果:

SELECT * FROM tb_characters,tb_colors;
Copy after login

bitsCN.com
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template