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写法。

相关推荐
开开心心就好23 分钟前
高效报价软件,简化商铺定价流程
服务器·数据库·安全·面试·职场和发展·电脑·symfony
钢铁男儿1 小时前
PyQt5高级界而控件(容器:装载更多的控件QDockWidget)
数据库·python·qt
阿蒙Amon4 小时前
C# Linq to SQL:数据库编程的解决方案
数据库·c#·linq
花花鱼8 小时前
android studio 设置让开发更加的方便,比如可以查看变量的类型,参数的名称等等
android·ide·android studio
互联网搬砖老肖8 小时前
运维打铁: MongoDB 数据库集群搭建与管理
运维·数据库·mongodb
典学长编程9 小时前
数据库Oracle从入门到精通!第四天(并发、锁、视图)
数据库·oracle
alexhilton9 小时前
为什么你的App总是忘记所有事情
android·kotlin·android jetpack
积跬步,慕至千里10 小时前
clickhouse数据库表和doris数据库表迁移starrocks数据库时建表注意事项总结
数据库·clickhouse
极限实验室10 小时前
搭建持久化的 INFINI Console 与 Easysearch 容器环境
数据库
星辰离彬10 小时前
Java 与 MySQL 性能优化:Java应用中MySQL慢SQL诊断与优化实战
java·后端·sql·mysql·性能优化