3
votes

I started with this INSERT INTO ON DUPLICATE KEY UPDATE MySQL statement.

INSERT INTO Table1 ( field1, field2)
VALUES (1, 2)
ON DUPLICATE KEY UPDATE field1 = 1, field2 = 2

Then, I encountered an error " a foreign key constraint fails".

I realize I needed to add another WHERE clause condition to satisfy the foreign key constraint with an inner join.

I tried something like this;

INSERT INTO Table1 ( field1, field2)
Inner Join Table2
ON Table2.id = Table1.field_id
VALUES (1, 2)
ON DUPLICATE KEY UPDATE field1 = 1, field2 = 2
WHERE Table2.addr='123456'

I get syntax error. What is the proper way to write this MySQL statement?

3

3 Answers

1
votes

I'm not sure exactly what you want to do. But, you can put any select statement in an insert . . . select statement and still use on duplicate key update. For instance:

insert into Table1(field1, field2)
    select 1, 2
    from table1 t1 join
         table2 t2
         on t2.id = t1.field_id
    where t2.addr = '123456'
    on duplicate key update field1 = 1, field2 = 2;
0
votes

Since you encountered a foreign key constraint, then you have to address in order for your INSERT to work.

Your query should look something like;

INSERT INTO Table1 ( field1, field2, foreign_key_id)
Select (1, 2, foreign_key_id)
where 
...
ON DUPLICATE KEY UPDATE field1 = 1, field2 = 2

I believe reading the answers on this question will solve your problem. Mysql: How to insert values in a table which has a foreign key

0
votes
   Declare
        @Field1 VARCHAR(255),  
        @Field2 VARCHAR(255)

   SET @Field1= 'Test'
   SET @Field2='ABC'

    IF EXISTS (SELECT * FROM ##Table1 WHERE ##Table1.Field1=@Field1 AND ##Table1.Field2=@Field2)

        BEGIN
            UPDATE ##Table1 SET Field1=@Field1,Field2=@Field2
        END 
        ELSE
        BEGIN
                INSERT INTO ##Table1 VALUES(@Field1,@Field2)
        END

    SELECT * FROM ##Table1