0

I have a table with the columns value1, value2 and value3.

Every few months, all rows will need to change their 'value1' to a different value. So far I have the following code and I cannot figure out for the life of me why it is not working. Instead of only modifying column one, it generates an entire new row of information.

Thanks in advance.

INSERT INTO table (value1, value2, value3)
            VALUES ('$valueForValue1', '$valueForValue2','$valueForValue3')
            ON DUPLICATE KEY UPDATE
                `value1`='$valueForValue1',
                `value2`='$valueForValue2',
                `value3`='$valueForValue3',
3
  • 3
    What indices/constraints do you have on the table? Besides ...all rows will need to change their 'value1' to a different value... looks like a job for UPDATE statement rather than INSERT if you really meant all rows. Can you elaborate a little bit more on what are you trying to achieve? Commented Nov 9, 2013 at 5:09
  • Forgive me, I am very new to MySQL. What do you mean indices/constraints? I haven't set any, if that helps. How would I go about implementing that? Commented Nov 9, 2013 at 5:20
  • I need value2 and value3 to stay the same, but value1 should be updated every few months. Commented Nov 9, 2013 at 5:20

2 Answers 2

1

In order to be able to change a value of value1 with ON DUPLICATE KEY clause you have to have either a UNIQUE constraint or a PRIMARY KEY on (value2, value3).

ALTER TABLE table1 ADD UNIQUE (value2, value3);

Now to simplify your insert statement you can also use VALUES() in ON DUPLICATE KEY like this

INSERT INTO Table1 (`value1`, `value2`, `value3`)
VALUES ('$valueForValue1', '$valueForValue2', '$valueForValue3')
ON DUPLICATE KEY UPDATE value1 = VALUES(value1);

Here is SQLFIddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly! Thank you so much!
1

The UPDATE action of the ON DUPLICATE KEY clause will only be executed if the row being inserted would cause the violation of a UNIQUE constraint. That means there needs to be a primary key or a unique index on the table.

If you want to modify existing rows, you'd really want to use an UPDATE statement.

To change the value in a column of existing rows, replacing 'oldvalue' with 'newvalue', you could do something like this:

UPDATE mytable
   SET col1 = 'newvalue'
 WHERE col1 = 'oldvalue'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.