时间:2021-07-01 10:21:17 帮助过:26人阅读
首先创建两张表
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
SELECT * FROM customer c LEFT JOIN t_user u ON c.`t_id` = u.id
查询结果为:
A为主表,B没有数据会自动补为 NULL
SELECT * FROM customer c RIGHT JOIN t_user u ON c.`t_id` = u.id
查询结果为:
B为主表,A查询不到数据会自动补为NULL
SELECT * FROM customer c INNER 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
查询结果为:
查询出不包含AB交集的A的部分,使用
u.id IS NULL
找到B为NULL的部分,也就是不含交集的部分,从而查询出不含AB交集的A的部分
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的部分
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
查询结果为:
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
查询结果为:
Mysql 的七种 join sql 编写
标签:engine ima default 主表 block where mysql code char