目录
前言
本文简单记录左连接各种情况产生的结果集数目,右连接类似
一、左连接是什么
简单来说就是left join,连接条件为on
二、表格举例
表A
id | name | sex | addr |
1 | Tom | 0 | asd |
2 | Jack | 0 | zxc |
表B
id | name | sex | addr |
1 | Tom | 0 | asd |
2 | Sam | 0 | asd |
3 | Bill | 0 | asd |
三、结果集举例
SELECT * FROM table_a a LEFT JOIN table_b b ON a.id = b.id; -- 2
id | name | sex | addr | id(1) | name(1) | sex(1) | addr(1) |
1 | Tom | 0 | asd | 1 | Tom | 0 | asd |
2 | Jack | 0 | zxc | 2 | Sam | 0 | asd |
结果1
SELECT * FROM table_a a LEFT JOIN table_b b ON a.addr = b.addr; -- 4
id | name | sex | addr | id(1) | name(1) | sex(1) | addr(1) |
1 | Tom | 0 | asd | 1 | Tom | 0 | asd |
1 | Tom | 0 | asd | 2 | Sam | 0 | asd |
1 | Tom | 0 | asd | 3 | Bill | 0 | asd |
2 | Jack | 0 | zxc |
结果2
SELECT * FROM table_a a LEFT JOIN table_b b ON a.sex = b.sex; -- 6
id | name | sex | addr | id(1) | name(1) | sex(1) | addr(1) |
1 | Tom | 0 | asd | 1 | Tom | 0 | asd |
2 | Jack | 0 | zxc | 1 | Tom | 0 | asd |
1 | Tom | 0 | asd | 2 | Sam | 0 | asd |
2 | Jack | 0 | zxc | 2 | Sam | 0 | asd |
1 | Tom | 0 | asd | 3 | Bill | 0 | asd |
2 | Jack | 0 | zxc | 3 | Bill | 0 | asd |
结果3
总结
left join结果集最多产生n*m条,最少产生n条(n<m)