mysql多表重复数据只保留一行的思路

一、问题描述

假设有3个表,test_a,test_b,test_c;

test_a和test_b中有些重复数据;

现在要把这2个表的数据同步到表c,但是重复数据只保留1行。

样例如下:


具体要求如下:

1.test_a与test_b中都存在的数据(根据card关联),以test_a为准,并且把authority字段拼起来(逗号分隔),移动到test_c

2.对于test_a不存在但是test_b存在的数据,以test_b为准,移动到test_c

3.对于test_a存在但是test_b不存在的数据,以test_a为准,移动到test_c

二、sql样例

1.首先查询到test_a不存在但是test_b存在的数据:

a 复制代码
SELECT
	NULL AS user_id,
	b.card,
	b. NAME,
	b.authority
FROM
	test_b b
LEFT JOIN test_a a ON b.card = a.card
WHERE
	a.id IS NULL

使用a.id is null,就说明是test_b存在、test_a不存在了;

然后可以把这部分数据存入test_c

2.然后查询test_a 存在 && ( test_b 存在 || test_b 不存在)的数据

a 复制代码
SELECT
	a.user_id,
	a.card,
	ifnull(a.NAME, b.NAME),
	CASE
WHEN a.authority IS NULL
AND b.authority IS NULL THEN
	NULL
WHEN a.authority IS NOT NULL
AND b.authority IS NOT NULL THEN
	concat(
		a.authority,
		',',
		b.authority
	)
WHEN a.authority IS NOT NULL
AND b.authority IS NULL THEN
	a.authority
WHEN a.authority IS NULL
AND b.authority IS NOT NULL THEN
	b.authority
ELSE
	a.authority
END AS authority
FROM
	test_a a
LEFT JOIN test_b b ON a.card = b.card

使用了ifnull(a.NAME, b.NAME),,可以当test_a表的数据为空时(不准确了),使用test_b表的数据;

注意这里有个坑,使用concat(a.authority,',',b.authority)时,如果有一个表的数据为null,那么最终结果就会是null,不符合预期;

a 复制代码
//这样有些问题
//select a.user_id,a.card,a.name,a.authority,b.authority,concat(a.authority,',',b.authority) from test_a a left join test_b b on a.card=b.card 

并且还需要判断是否需要拼接,;

因此sql中使用了case when写法。

相关推荐
雨白6 小时前
单例设计模式:从 Java/Kotlin 实现到 Android 实战
android
千寻技术帮7 小时前
10454_基于Springboot的企业购销链管理系统
spring boot·mysql·vue·毕业设计·进销存
bksczm8 小时前
Redis Cluster 分片集群详解:槽路由、故障判定与扩缩容
数据库·redis·分布式
ServBay10 小时前
AI编程越来越强,为什么软件漏洞却是一个没少?MySQL又爆高危漏洞了
后端·mysql
黑十10 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
FungLeo10 小时前
FengCMS · PHP+MySQL 升级实录 · Web 入口收敛:Apache/Nginx 白名单挡住配置、安装 SQL、上传脚本直连
前端·mysql·php·安全加固·fengcms
Databend10 小时前
OpenRaft 自定义 Membership,按部署拓扑选择 Quorum
大数据·数据库·数据分析
Databend11 小时前
用 SQL 排查支付故障,OpenTelemetry 接入 Databend Cloud 实战
大数据·数据库·sql
hai_android11 小时前
一行 asLiveData,背后是一座生命周期的桥
android·java·kotlin
kyle~11 小时前
SQLite -- 低成本持久化能力
数据库·sqlite