简体   繁体   中英

how to merge rows with the same column in sql like this?

Table1: Factor_Name

ID NAME
1  A
2  A
3  B

Table2: Sample_Info

   ID   FACTOR_ID   INFO
   1    1           Sample_A
   2    2           Sample_B
   3    3           Sample_C

I want to merge the column in the 2 tables if the factor names are same in table1, this is the expected table:

Table1: Factor_Name

ID NAME
1  A
2  B

Table2: Sample_Info

   ID   FACTOR_ID   INFO
   1    1           Sample_A
   2    1           Sample_B
   3    2           Sample_C

How can I do that in mysql?

You're going to want to do this by first duplicating the tables you currently have:

CREATE TEMPORARY TABLE Factor_Name_Temp as (SELECT * 
                                            FROM Factor_Name) 

CREATE TEMPORARY TABLE Sample_Info_Temp as (SELECT * 
                                            FROM Sample_Info) 

Then, you're going to need to clear the contents of the existing tables. You also appear to want to reset the id columns. This could be slightly dangerous, depending on how many other tables reference these values. But either way...

Then, insert the data from the 'temp' tables back into the original tables. Leave off the id column if you're having them re-generated, otherwise this will choose the initial 'minimum' value (ie, there'll be gaps).

INSERT Factor_Name (id, name) 
SELECT MIN(id), name
FROM Factor_Name_Temp
GROUP BY name

INSERT Sample_Info (id, factor_id, info)
SELECT Sample_Info_Temp.id, Factor_Name.id, Sample_Info_Temp.info
FROM Sample_Info_Temp
JOIN Factor_Name_Temp
  ON Factor_Name_Temp.id = Sample_Info_Temp.factor_id
JOIN Factor_Name
  ON Factor_Name.name = Factor_Name_Temp.name

Don't forget to clean up after yourself!

(Statements untested - I lack a mySQL instance, and SQL Fiddle isn't completely conductive to this).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM