简体   繁体   中英

PHP, MySQL, Merge 2 tables into 1, but if there is same value in row change value

So I have two tables with same columns, and same kind of values goes inside. Lets call them table_1 and table_2. The thing is I want to merge them into 1 table named table_3.

Problem I encounter is that some values in table_1 and table_2 are same and when that happens I need to change some value.

This is how table_1 looks

Table_1

id, record_id, stuff_to_change, something_else

This is how table_2 looks

Table 2

id, record_id, stuff_to_change, something_else

This is how table_3 looks

Table 3

id, record_id, stuff_to_change, something_else

The thing now is, that I need to compare record_id from table_1 and table_2, and if they are different just copy it as it is to table_3, if it is different I need to change stuff_to_change in table_3. It needs to have different value.

So in pseudocode it would be something like this:

for(i=0;i<end_of_table;i++)
{
   for(j=0;j<end_of_second_table;j++)
   {
       if(record_id[i]==record_if[j]
       {
            record_id[i].stuff_to_change='SOMETHING';
            mysqli_query($conn, "INSERT INTO table_3 (record_id, stuff_to_change, something_else) VALUES (record_id[i],stuff_to_change[i],something_else[i]");
       }else{
            mysqli_query($conn, "INSERT INTO table_3 (record_id, stuff_to_change, something_else) VALUES (record_id[i],stuff_to_change[i],something_else[i]");
       }           
   }
}

Well this pseudo code is not complete, and I am not sure how to do it. So combine two tables into one, but if there is same value in record_id then change stuff_to_change, is record_id is unique then just copy it to table_3. Also important to notice is that if there is same record_id in 2 tables I do not need both of them, just 1 but with different stuff_to_change value.

I will be very grateful for help, I tried with union, and parsing it into values inside php, but nothing works for me

You can use CREATE TABLE ... SELECT statement.

INSERT INTO table3 
SELECT * FROM tabel1
UNION
SELECT * FROM tabel2

since you have the same columns in all three of them ...

In a general case you should work with column lists like

INSERT INTO table3 (col1, col2, col3)
SELECT col1, col2, col3 FROM tabel1
UNION
SELECT col1, col2, col3 FROM tabel2

This way you avoid trouble with auto_increment id-columns. Also You should consider using UNION ALL since UNION filters out duplicate lines and therefore will take longer on large tables.

This may help you to solve the problem.

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