时间:2022-09-11 11:26:43 | 栏目:Mysql | 点击:次
SELECT T1.ID,T2.ID,T1.`NAME`,T2.`NAME` FROM A T1 LEFT JOIN B T2 ON T1.ID = T2.ID AND COALESCE(T1.ID,'') <> '' AND COALESCE(T2.ID,'') <> '' WHERE T1.`NAME` <> T2.`NAME`;
判断两表某些字段是否相同,3种查询结果相同
-- 写法01 SELECT COUNT(1) FROM ( SELECT DISTINCT ID,`NAME` FROM A ) T1; -- 写法02 SELECT COUNT(1) FROM ( SELECT DISTINCT ID,`NAME` FROM B ) T2; -- 写法03 SELECT COUNT(1) FROM ( SELECT DISTINCT ID,`NAME` FROM A UNION SELECT DISTINCT ID,`NAME` FROM B ) T0;
not in与exists
找出只存在于T2,不在T1中的那些id
-- 写法01 SELECT T2.`NAME`,T2.* FROM A T2 WHERE T2.`NAME` IS NOT NULL AND NOT EXISTS (SELECT 1 FROM B T1 WHERE T1.ID = T2.ID); -- 写法02 SELECT T2.`NAME`,T2.* FROM A T2 WHERE T2.`NAME` IS NOT NULL AND T2.ID NOT IN (SELECT T1.ID FROM B T1 );
测试id与name的一对多关系以下SQL会报错,报错原因 GROUP BY
SELECT ID,`NAME`,COUNT(*) FROM A GROUP BY ID HAVING COUNT(`NAME`)>1;
修改后:
SELECT ID, COUNT(DISTINCT `NAME`) FROM A GROUP BY ID HAVING COUNT(DISTINCT `NAME`)>1;
这样就说明id与name是一对多的关系
扩展:多对多关系,上述SQL中id与name位置互换后,查询有值,就说明两者是多对多关系
-- 写法01 SELECT ID FROM A GROUP BY ID HAVING COUNT(*)>1; -- 写法02 SELECT ID,COUNT(ID) FROM A GROUP BY ID HAVING COUNT(ID)>1;
SELECT ID,`NAME` FROM A GROUP BY ID,`NAME` HAVING COUNT(*)>1 ORDER BY ID;
-- 建表 CREATE TABLE IF NOT EXISTS TEST01.A ( ID VARCHAR(50) COMMENT 'ID号' -- 01 ,NUMS INT COMMENT '数字' -- 02 ,NAME VARCHAR(50) COMMENT '名字' -- 03 ) COMMENT 'A表' STORED AS PARQUET ; -- 插数 INSERT INTO TEST01.A (ID,NUMS,NAME) VALUES ('01',1,NULL); INSERT INTO TEST01.A (ID,NUMS,NAME) VALUES ('02',2,''); INSERT INTO TEST01.A (ID,NUMS,NAME) VALUES ('03',3,'c'); -- 删数 DELETE FROM TEST01.A WHERE ID = '04'; -- 删表 DROP TABLE IF EXISTS TEST01.A;