MySQL 分組取最新的一條

1.MySQL 分組取最新的一條

2.MySQL not in not exists 

CREATE TABLE `test_dept`  (
  `deptid` int(11) NOT NULL,
  `deptname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`deptid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;


INSERT INTO `test_dept` VALUES (180001, '總公司');
INSERT INTO `test_dept` VALUES (180002, '運維部');
INSERT INTO `test_dept` VALUES (180003, '開發部');



CREATE TABLE `test_cust`  (
  `custid` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '0' COMMENT '客戶編號',
  `cname` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '' COMMENT '客戶名稱',
  `deptid` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '' COMMENT '所屬部門',
  `updatetime` datetime(0) DEFAULT NULL COMMENT '最後修改時間'
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

INSERT INTO `test_cust` VALUES ('10001', '張三', '180003', '2020-02-01 13:50:42');
INSERT INTO `test_cust` VALUES ('10001', '張三', '180003', '2020-03-24 13:50:48');
INSERT INTO `test_cust` VALUES ('10002', '李四', '666', '2020-03-10 14:02:29');



####分組後取最後修改的那一條
select * from test_cust tc
where not exists(select 1  from test_cust where custid=tc.custid and updatetime>tc.updatetime)
GROUP BY custid;


####in 和 exits 和分組後取最後修改的那一條
select * from test_cust 
	where test_cust.deptid not in (select deptid from test_dept where test_dept.deptid=test_cust.deptid);
select * from test_cust 
	where test_cust.deptid in (select deptid from test_dept where test_dept.deptid=test_cust.deptid);

select * from test_cust 
	where exists  (select deptid from test_dept where test_dept.deptid=test_cust.deptid);
select * from test_cust 
where not exists  (select deptid from test_dept where test_dept.deptid=test_cust.deptid);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章