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

一、问题描述

假设有3个表,test_atest_btest_c

test_atest_b中有些重复数据;

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

样例如下:


具体要求如下:

1.test_atest_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写法。

相关推荐
hjlgs3 小时前
framework修改快速验证
android
2501_941148153 小时前
多语言微服务架构与边缘计算技术实践:Python、Java、C++、Go深度解析
数据库
游戏开发爱好者83 小时前
iOS 开发者的安全加固工具,从源码到成品 IPA 的多层防护体系实践
android·安全·ios·小程序·uni-app·cocoa·iphone
计算机毕设小月哥3 小时前
【Hadoop+Spark+python毕设】智能制造生产效能分析与可视化系统、计算机毕业设计、包括数据爬取、Spark、数据分析、数据可视化、Hadoop
后端·python·mysql
w***z503 小时前
MYSQL 创建索引
数据库·mysql
j***51893 小时前
Java进阶,时间与日期,包装类,正则表达式
java·mysql·正则表达式
安卓理事人4 小时前
安卓内存泄露排查LeakCanary
android
章鱼哥7304 小时前
[特殊字符] SpringBoot 自定义系统健康检测:数据库、Redis、表统计、更新时长、系统性能全链路监控
java·数据库·redis
5***E6854 小时前
MySQL:drop、delete与truncate区别
数据库·mysql
记得记得就1515 小时前
【MySQL数据库管理】
数据库·mysql·oracle