先來創建兩個表和數據 CREATE TABLE `test1` (`id` int NOT NULL,`name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,`age` int DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;CREATE TABLE `test2` (`id` int NOT NULL,`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,`age` int DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;INSERT INTO `test`.`test1` (`id`, `name`, `age`) VALUES (1, 't11', 10);
INSERT INTO `test`.`test1` (`id`, `name`, `age`) VALUES (2, 't12', 11);
INSERT INTO `test`.`test1` (`id`, `name`, `age`) VALUES (3, 't13', 12);INSERT INTO `test`.`test2` (`id`, `name`, `age`) VALUES (1, 't21', 20);
INSERT INTO `test`.`test2` (`id`, `name`, `age`) VALUES (4, 't24', 24);
INSERT INTO `test`.`test2` (`id`, `name`, `age`) VALUES (5, 't25', 25);
根據數據分析,那么差集應該是id等于2,3,4,5的數據?
直接查出各自缺的那部分,再UNION合并即可 SELECTt1.*
FROMtest1 t1LEFT JOIN test2 t2 ON t1.id = t2.id
WHEREt2.id IS NULL
UNION
SELECTt2.*
FROMtest1 t1right JOIN test2 t2 ON t1.id = t2.id
WHEREt1.id IS NULL 以上就是獲取兩個差集的整個過程了,如果有哪位大佬有更好的思路,歡迎指正; 以下是另一位大佬的求差集的sql和鏈接,有興趣的朋友可以去看看; select id FROM usertable LEFT JOIN
(select id as i from blog) as t1
ON usertable.id=t1.i where t1.i IS NULL 【Mysql】求兩個表(查詢結果)的差集_編程記錄,親測有效-CSDN博客_mysql求差集