Skip to content
Advertisement

MYSQL moving data after distinct

I have data I am pulling from one table to another table but I have a Primary key on the ID column. how do I pull the rest of the data after a Select distinct to make sure I don’t have duplicates in the primary?

INSERT INTO `goac`.`store`(`STORE_ID`)
select distinct STORE_ID
from ods_sale_large

for example I have this

where I have gotten the distinct store_id from it and inserted into the table but I need the rest of the data to come with.

Advertisement

Answer

I guess it is in case of duplicate keys between existing records in the target table and the source query. You can use then INSERT .. ON DUPLICATE KEY UPDATE . As an example, If your table goac.store has a primary key on STORE_ID and a field DUPLICATE_STORE_ID, you can insert only the missing keys from ods_sale_large as new records and store the duplicate keys between ods_sale_large and goac.store in the field DUPLICATE_STORE_ID of the existing records :

INSERT INTO `goac`.`store` (`STORE_ID`)
select distinct STORE_ID from ods_sale_large
ON DUPLICATE KEY UPDATE `DUPLICATE_STORE_ID` = VALUES(`STORE_ID`);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement