一、基本定义:
left join (左连接):返回包括左表中的所有记录和右表中连接字段相等的记录。
right join (右连接):返回包括右表中的所有记录和左表中连接字段相等的记录。
inner join (等值连接或者叫内连接):只返回两个表中连接字段相等的行。
full join (全外连接):返回左右表中所有的记录和左右表中连接字段相等的记录。
二、样例:
1. 建表语句:
表people:
CREATE TABLE `people` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
表position:
CREATE TABLE `position` (
`id` int(11) DEFAULT NULL,
`people_id` int(11) DEFAULT NULL,
`position` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.内连接(只有2张表匹配的行才能显示):
SELECT * FROM people INNER JOIN POSITION ON people.`id` = position.`id`
说明:组合两个表中的记录,返回关联字段相符的记录,也就是返回两个表的交集部分。
3.左连接(左边表不加限制):
SELECT * FROM people LEFT JOIN POSITION ON people.`id` = position.`id`
说明:
left join 是left outer join的简写,它的全称是左外连接,是外连接中的一种。
左(外)连接,左表(people_table)的记录将会全部表示出来,而右表(position_table)只会显示符合搜索条件的记录。右表记录不足的地方均为NULL。
4.右连接(右表不加限制):
SELECT * FROM people RIGHT JOIN POSITION ON people.`id` = position.`id`
说明:
right join是right outer join的简写,它的全称是右外连接,是外连接中的一种。
与左(外)连接相反,右(外)连接,左表(people)只会显示符合搜索条件的记录,而右表(position)的记录将会全部表示出来。左表记录不足的地方均为NULL。
5.全外连接(左右两张表都不加限制):
MySql中不支持此种方式,可以用其他方式代替解决,比如join+union的方式来代替。
MySQL Full Join的实现 因为MySQL不支持FULL JOIN,下面是替代方法
left join + union(可去除重复数据)+ right join
SELECT * FROM people LEFT JOIN POSITION ON people.`id` = position.`id`
UNION
SELECT * FROM people RIGHT JOIN POSITION ON people.`id` = position.`id`
说明:
全外连接会将左右两表的数据都列出来
另外在网上浏览相关MySql连接的内容,看到了这些,暂时没有太懂,现在与君共享
三、补充,MySQL如何执行关联查询
MySQL认为任何一个查询都是一次“关联”,并不仅仅是一个查询需要到两个表匹配才叫关联,所以在MySQL中,每一个查询,每一个片段(包括子查询,甚至基于单表查询)都可以是一次关联。
当前MySQL关联执行的策略很简单:MySQL对任何关联都执行嵌套循环关联操作,即MySQL先在一个表中循环取出单条数据,然后在嵌套循环到下一个表中寻找匹配的行,依次下去,直到找到所有表中匹配的行为止。然后根据各个表匹配的行,返回查询中需要的各个列。请看下面的例子中的简单的查询:
查询语句:select tbl1.col1, tbl2.col2 from tbl1 inner join tbl2 using(col3) where tbl1.col1 in (5, 6);
假设MySQL按照查询中的表顺序进行关联操作,我们则可以用下面的伪代码表示MySQL将如何完成这个查询:
outer_iter = iterator over tbl1 where col1 in (5, 6)
outer_row = outer_iter.next
while outer_row
inner_iter = iterator over tbl2 where col3 = outer_row.col3
inner_row = inner_iter.next
while inner_row
output [ outer_row.col1, inner_row.col2]
inner_row = inner_iter.next
end
outer_row = outer_iter.next
end
上面的执行计划对于单表查询和多表关联查询都适用,如果是一个单表查询,那么只需要上面外层的基本操作。对于外连接,上面的执行过程仍然适用。例如,我们将上面的查询语句修改如下:
select tbl1.col1, tbl2.col2 from tbl1 left outer join tbl2 using(col3) where tbl1.col1 in (5, 6);
那么,对应的伪代码如下:
outer_iter = iterator over tbl1 where col1 in (5, 6)
outer_row = outer_iter.next
while outer_row
inner_iter = iterator over tbl2 where col3 = outer_row.col3
inner_row = inner_iter.next
if inner_row
while inner_row
output [ outer_row.col1, inner_row.col2]
inner_row = inner_iter.next
end
else
output [ outer_row.col1, null]
end
outer_row = outer_iter.next
end
转载:https://blog.csdn.net/weixin_40009846/article/details/101686677