示例: 建立測試表,並初始化數據測試
CREATE TABLE `test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `base_org_id` int(11) DEFAULT NULL, `account_period` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, PRIMARY KEY (`id`), KEY `base_org_index` (`base_org_id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (1, 1, '2019-07'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (2, 1, '2019-08'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (3, 1, '2019-09'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (4, 2, '2019-07'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (5, 2, '2019-08'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (6, 2, '2019-09'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (7, 2, '2019-10'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (8, 2, '2019-11'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (9, 2, '2019-12'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (10, 3, '2019-07'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (11, 3, '2019-08'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (12, 4, '2019-07'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (13, 5, '2019-07'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (14, 6, '2019-07'); INSERT INTO `mytest`.`test`(`id`, `base_org_id`, `account_period`) VALUES (15, 7, '2019-07');
執行查詢code
SELECT T1.* FROM test T1 LEFT JOIN test T2 ON T1.base\_org\_id = T2.base\_org\_id AND T1.id < T2.id WHERE T2.id IS NULL
思路:io
對同一張表進行左關聯,示例中以好比base_org_id爲關聯關係,好比base_org_id 爲1的數據有2條,關聯後base_org_id爲1的數據有4條,這時候關鍵一個條件T1.id < T2.id做用就體現出來了,T1的ID爲3時 T2中的ID沒有超過三的,因此此時只有一條數據T1中的數據而T2中沒有數據。最後條件T2.id IS NULL過濾出來,即須要的數據