2

I have a MySQL table with an autoincremented primary key, and a column for a person's name, and some data.

Is there a MySQL query where I can insert a new row if the name of the person is unique, but if it's a duplicate name, then I would update that row?

I.e.

ID, Name,        Data
1 , Michael,     x
2 , Stephen,     y
3 , Christopher, z

If I were to add a "Michael" to the database with "qq" data, I would want the database to look like this:

ID, Name,        Data
1 , Michael,     qq
2 , Stephen,     y
3 , Christopher, z

If I were to add "John" with "zz" data, the database would look like this:

ID, Name,        Data
1 , Michael,     x
2 , Stephen,     y
3 , Christopher, z
4 , John,        zz

I know of the command, ON DUPLICATE KEY UPDATE, but I only want to update if the name is the same, not if the primary key is the same.

3
  • had you heard about stored procedures ? they make this very simple mysqltutorial.org/mysql-stored-procedure-tutorial.aspx Commented Jan 26, 2013 at 18:46
  • 1
    Just add an UNIQUE INDEX on Name, nothing big to lose. Commented Jan 26, 2013 at 18:51
  • Thank you for the link legendinmaking. Commented Jan 26, 2013 at 19:01

2 Answers 2

7

Create a UNIQUE index on Name. ON DUPLICATE KEY UPDATE will then work correctly.

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

Comments

0

Create a stored procedure and simply call it in your query code

PROCEDURE:

   DROP PROCEDURE IF EXISTS InsUpdTable $$
        CREATE PROCEDURE InsUpdTable
        (
          IN _name VARCHAR(45),
          IN _data VARCHAR(45)
        )
        BEGIN
        if exists (select ID from mytable where name = _name)
        Then
          update mytable set data = _data where name=_name;
        else
          insert into mytable(name, data) values(_name, _data);
        END IF;
        END $$
        DELIMITER ;

Query:

call InsUpdTable('John','zzz')

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.