php - Insert records if not exist to specific columns with special conditions in MySQL -
i have csv file i'd insert table (let's call my_table).
for task, load csv file new temporary table called temp_table (has same features/structure my_table). values don't exist should inserted my_table there conditions must fulfilled:
if value in column letter in my_table doesn't exist then:
- insert value in 'letter' column letter in my_table
- also insert 'num' value column num in my_table
if value 'letter' exists, value in 'num' missing in my_table , update record in column 'num'
here example table in temp_table (left) , my_table (right):
temp_table my_table letter num letter num 1 aab 123 aab 123 2 aac 123 --- --- (both don't exist) 3 bba 234 bba --- (only num doesn't exist) result my_table: letter num 1 aab 123 2 aac 123 3 bba 234
*order (id) doesn't matter.
edit: can see value in line 1 isn't inserted my_table because value aab exists. in second line, aac doesn't exist , therefore inserted value of num. in third line, bba needs updated, column num gets value.
does knows how in mysql?
or easier/make more sense try write in php?
additional: came far in order overcome part 1 -
insert my_table (letter) select distinct letter temp_table not exists (select * my_table my_table.letter = temp_table.letter);
the above mentioned job partially. inserts values not exists in letter only. part two? inserting rows of column num in rows in letter missing? in row 2 of example.. purpose tried:
insert my_table (letter, num) select distinct letter, num temp_table not exists (select * my_table my_table.letter = temp_table.letter , my_table.num = temp_table.num);
however, didn’t work wanted. although did skip first row , indeed inserted row (2) should have:
2 aac 123
it inserted row:
letter num 1 aab 123 2 aac 123 3 bba 4 bba 234
as new row, , shouldn’t have occurred! because bba exists , condition part 3.
so mentioned before, value column num should inserted, if , if row in column letter exists !!
if have unique constraint on letter
can use mysql's insert...on duplicate key update syntax, little bit of logic num
column:
insert my_table (letter, num) select letter, num temp_table on duplicate key update num = coalesce(num, values(num));
Comments
Post a Comment