首先创建两张表
CREATE TABLE `t_user` (
`id` bigint(16) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`age` int(4) NOT NULL,
`gender` tinyint(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
CREATE TABLE `customer` (
`id` bigint(16) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`age` int(4) NOT NULL,
`mobile` char(11) NOT NULL,
`t_id` bigint(16) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
LEFT JOIN 查询 A(包含AB的交集)
SELECT * FROM customer c LEFT JOIN t_user u ON c.`t_id` = u.id
查询结果为:
A为主表,B没有数据会自动补为 NULL
RIGHT JOIN 查询 B (包含AB的交集)
SELECT * FROM customer c RIGHT JOIN t_user u ON c.`t_id` = u.id
查询结果为:
B为主表,A查询不到数据会自动补为NULL
INNER JOIN 查询 AB的交集
SELECT * FROM customer c INNER JOIN t_user u ON c.`t_id` = u.id
查询结果为:
查询A和B的交集
LEFT JOIN 查询 A (不包含AB的交集)
SELECT * FROM customer c LEFT JOIN t_user u ON c.`t_id` = u.id WHERE u.id IS NULL
查询结果为:
查询出不包含AB交集的A的部分,使用
u.id IS NULL
找到B为NULL的部分,也就是不含交集的部分,从而查询出不含AB交集的A的部分
RIGHT JOIN 查询B (不包含AB的交集)
SELECT * FROM customer c RIGHT JOIN t_user u ON c.`t_id` = u.id WHERE c.id IS NULL
查询结果为:
原理与上面一样,通过c.id IS NULL 查询出不包含AB交集的B的部分
查询A和B的全部
SELECT * FROM customer c LEFT JOIN t_user u ON c.`t_id` = u.id
UNION
SELECT * FROM customer c RIGHT JOIN t_user u ON c.`t_id` = u.id
查询结果为:
查询A B的独有
SELECT * FROM customer c LEFT JOIN t_user u ON c.`t_id` = u.id WHERE u.id IS NULL
UNION
SELECT * FROM customer c RIGHT JOIN t_user u ON c.`t_id` = u.id WHERE c.id IS NULL
查询结果为:
原文地址:https://www.cnblogs.com/Godfunc/p/9693884.html
时间: 2024-10-15 21:21:08