Created
April 20, 2022 13:11
-
-
Save nadyshalaby/dc88997cc5f81ef6661e35a8c207664a to your computer and use it in GitHub Desktop.
This sql script can merge two tables with different columns without carrying out the headache of specifying the whole list of column names. This script can guess the match column names and remove duplicates on insertion process.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SET @target_table = '`klame_new`.`url`'; | |
SET @source_table = '`klame_url`.`url`'; | |
SELECT GROUP_CONCAT(column_name) | |
FROM INFORMATION_SCHEMA.COLUMNS a | |
WHERE a.TABLE_NAME = 'url' | |
AND a.TABLE_SCHEMA = 'klame_url' | |
AND a.COLUMN_NAME IN ( | |
SELECT b.COLUMN_NAME | |
FROM INFORMATION_SCHEMA.COLUMNS b | |
WHERE b.TABLE_NAME = 'url' | |
AND b.TABLE_SCHEMA = 'klame_new' | |
) INTO @columns; | |
SET @s = CONCAT('REPLACE INTO ', @target_table , ' (',@columns,') ' , ' SELECT ', @columns ,' FROM ', @target_table ,' UNION ALL SELECT ', @columns , ' FROM ', @source_table); | |
PREPARE stmt FROM @s; | |
EXECUTE stmt; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment