SQL多表多字段比对方法实例代码

2022-07-15,,,,

表-表比较

整体思路

  • 两张表条数一样
    • 条数相同是前提,然后比较字段值才有意义
  • 两表字段值完全相同【两表所有字段的值相同】
    • 两表所有字段union后,条数与另一张表条数一样
  • 两表字段值部分相同【两表部分字段的值相同】
    • 原理:union有去重功能
    • 两表部分字段union后,条数与另一张的count(distinct 部分字段)一样
  • 找出不同字段的明细

找出不同字段的明细

t1/t2两表id相同的部分,是否存在不同name

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表独有的id

找出只存在于t2,不在t1中的那些id

  • 下面2种写法结果一样
-- 写法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位置互换后,查询有值,就说明两者是多对多关系

证明id字段不是主键

  • 下面2种写法结果一样
-- 写法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;

证明id, name字段不是联合主键

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;

总结 

到此这篇关于sql多表多字比对方法的文章就介绍到这了,更多相关sql多表多字段比对内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《SQL多表多字段比对方法实例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。