我是靠谱客的博主 尊敬月光,这篇文章主要介绍MySQL比较两张表数据相同、不同结果记录两张表:水果设备表sb_fruit、系统设备表xt_fruit,比较两张表中相同、不同的数据结果。,现在分享给大家,希望可以做个参考。

两张表:水果设备表sb_fruit、系统设备表xt_fruit,比较两张表中相同、不同的数据结果。

自己开始尝试写的方法:

(1)设备与系统共有数据:

select sb.id,sb.name_idnumber,xt.id,xt.name_idnumber
from sb_fruit sb,xt_fruit xt
where sb.name_idnumber = xt.name_idnumber; 

(2)设备多出数据:

select sb.id,sb.name_idnumber
from sb_fruit sb
where sb.id not in
(
select sb.id
from sb_fruit sb,xt_fruit xt
where sb.name_idnumber = xt.name_idnumber
);

(3)系统多出数据:

select xt.id,xt.name_idnumber 
from xt_fruit xt 
where xt.id not in 
(
select xt.id 
from sb_fruit sb,xt_fruit xt 
where sb.name_idnumber = xt.name_idnumber 
);

后学到另一种方法,比较两张表数据的不匹配记录、匹配记录。

参考网址:【MySQL比较两个表不同的数据 - MySQL教程 https://www.yiibai.com/mysql/compare-two-tables-to-find-unmatched-records-mysql.html】


步骤:
    (1)首先,使用UNION语句来组合两个表中的行; 仅包需要比较的列。返回的结果集用于比较。
    (2)第二步,根据需要比较的主键和列分组记录。如果需要比较的列中的值相同,则COUNT(*)返回2,否则COUNT(*)返回1。

    

两张表中各自不同的数据:

(1)此为二者多出结果的混合数据:
select id,name_idnumber 
from 
(
select CONCAT('sb_',sb.id) id,sb.name_idnumber 
from sb_fruit sb 
UNION ALL 
select CONCAT('xt_',xt.id) id,xt.name_idnumber 
from xt_fruit xt 
) t 
GROUP BY name_idnumber 
HAVING count(*) = 1;      
(2)此为单看设备多出结果:
select id,name_idnumber 
from 
(
select CONCAT('sb_',sb.id) id,sb.name_idnumber 
from sb_fruit sb 
UNION ALL 
select CONCAT('xt_',xt.id) id,xt.name_idnumber 
from xt_fruit xt 
) t 
GROUP BY name_idnumber 
HAVING count(*) = 1
and id like '%sb_%';        
(3)此为单看系统多出结果:
select id,name_idnumber 
from 
(
select CONCAT('sb_',sb.id) id,sb.name_idnumber 
from sb_fruit sb 
UNION ALL 
select CONCAT('xt_',xt.id) id,xt.name_idnumber 
from xt_fruit xt 
) t 
GROUP BY name_idnumber 
HAVING count(*) = 1
  
and id like '%xt_%';        

查看两张表的相同数据:

select name_idnumber 
from 
(
select sb.name_idnumber 
from sb_fruit sb 
UNION ALL 
select xt.name_idnumber 
from xt_fruit xt 
) t 
GROUP BY name_idnumber 
HAVING count(*) = 2;

最后

以上就是尊敬月光最近收集整理的关于MySQL比较两张表数据相同、不同结果记录两张表:水果设备表sb_fruit、系统设备表xt_fruit,比较两张表中相同、不同的数据结果。的全部内容,更多相关MySQL比较两张表数据相同、不同结果记录两张表:水果设备表sb_fruit、系统设备表xt_fruit,比较两张表中相同、不同内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部