1. INNER JOIN 内连接
2. LEFT JOIN 左连接
5. LEFT JOIN EXCLUDING INNER JOIN 左连接-内连接
6. RIGHT JOIN EXCLUDING INNER JOIN 右连接-内连接
7. OUTER JOIN EXCLUDING INNER JOIN 外连接-内连接
建表
CREATE TABLE tbl_dep(id INT(11) NOT NULL AUTO_INCREMENT,
deptName VARCHAR(22) DEFAULT NULL,
addr VARCHAR(22) DEFAULT NULL,
PRIMARY KEY(id)
)ENGINE = INNODB DEFAULT CHARSET=utf8;
CREATE TABLE tbl_emp(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(22) DEFAULT NULL,
`deptId` VARCHAR(22) DEFAULT NULL,
PRIMARY KEY (`id`),
#constraint `fk_deptId` foreign key (`deptId`) references tbl_dep(id);
)engine=innodb default charset =utf8;
插入数据
INSERT INTO tbl_dep(deptName,addr) VALUES('hr','111');
INSERT INTO tbl_dep(deptName,addr) VALUES('bd','112');
INSERT INTO tbl_dep(deptName,addr) VALUES('vb','113');
INSERT INTO tbl_dep(deptName,addr) VALUES('sd','114');
INSERT INTO tbl_dep(deptName,addr) VALUES('yy','115');
INSERT INTO tbl_emp(name,deptId) VALUES('k8',1);
INSERT INTO tbl_emp(name,deptId) VALUES('k6',2);
INSERT INTO tbl_emp(name,deptId) VALUES('k4',3);
INSERT INTO tbl_emp(name,deptId) VALUES('k4',11);
七种join理论。
内连接(两表的共有部分)
SELECT * FROM tbl_dep d INNER JOIN tbl_emp e ON d.id=e.deptId;
左连接(左表的全部,右表不满足补NULL)
SELECT * FROM tbl_dep d LEFT JOIN tbl_emp e ON d.id=e.deptId;
右连接(右表的全部,左表不满足的补NULL)
SELECT * FROM tbl_dep d RIGHT JOIN tbl_emp e ON d.id=e.deptId;
特殊的左连接,(显示为左表的独有的数据)
说明:查询tbl_dep 表中跟tbl_emp 表无关联关系的数据,即tbl_dep 独占,且tbl_emp 表的显示列补NULL;
SELECT * FROM tbl_dep d LEFT JOIN tbl_emp e ON d.id=e.deptId WHERE e.deptId IS NULL;
特殊的右连接(显示为右表的独有的数据 )
说明:查询tbl_emp 表中跟tbl_dep 表无关联关系的数据,即tbl_emp 独占,且tbl_dep 表的显示列补NULL;
SELECT * FROM tbl_dep d RIGHT JOIN tbl_emp e ON d.id=e.deptId WHERE d.id IS NULL;
全连接(显示全部数据)(mysql 不支持 full outer join)
UNION :有去重的功能。
SELECT * FROM tbl_dep d LEFT JOIN tbl_emp e ON d.id=e.deptId UNION
SELECT * FROM tbl_dep d RIGHT JOIN tbl_emp e ON d.id=e.deptId;
显示两表的独有的数据
SELECT * FROM tbl_dep d LEFT JOIN tbl_emp e ON d.id=e.deptId WHERE e.deptId IS NULL UNION
SELECT * FROM tbl_dep d RIGHT JOIN tbl_emp e ON d.id=e.deptId WHERE d.id IS NULL;