Make a conditional update on ON DUPLICATE KEY

Asked

Viewed 975 times

4

I have a query that takes the data from a . csv and inserts the data into the table.

If the position is the same it updates the fields. I need that in addition to checking the position the query check whether status is different from 1 (status <> 1) to update.

That one status is not passed by . csv is only registered in the database and cannot update the records that are with status = 1.

How to do this?

$import=
       "INSERT INTO registros (NAME, position, price)
        VALUES
        (
         '$data[1]',
         '$data[2]',
         '$data[3]'
        ) ON DUPLICATE KEY UPDATE position = position,
        NAME = '$data[1]',
        position = '$data[2]',
        price = '$data[3]',
        qty_try = 0";

2 answers

5


Use the function IF()

INSERT INTO registros (NAME, position, price)
    VALUES
    (
     '$data[1]',
     '$data[2]',
     '$data[3]'
    ) ON DUPLICATE KEY UPDATE 
            /* SE  status atual for diferente de 1
               quando tivermos um position que 
               já existe     ,                           SE TRUE, SE FALSE */
    NAME     = IF(status <> 1,                        '$data[1]',     NAME),
    price    = IF(status <> 1,                        '$data[3]',    price),
    qty_try  = IF(status <> 1,                                 0,  qty_try);  

Note: No need to check if field position is the same as what is being inserted if it has a CONSTRAINT UNIQUE as you commented in @Bacco’s reply, since the ON DUPLICATE KEY UPDATE will be executed only when you have a INSERT with a position that already exists.

Reference:
http://thewebfellas.com/blog/2010/1/18/conditional-duplicate-key-updates-with-mysql

  • The value of status is that of the record where the DUPLICATE KEY was found.

  • That query worked, thank you very much Thomas. the status value is a field that is changed by another query called through an api when I pass a url with name && price, then in this query it changes the status to 1. In the case of my question is a query with database updates made through an import. I couldn’t try the project because all I have to do is go to the work bank, but thank you for helping Bacco

  • @Rafaelribeiro If you tested and solved, I think it is a good way out. You cannot specify a condition in the UPDATE itself, but as an argument to IF inline to keep the parameter equal or not, according to the status, is an interesting output (and has my +1).

  • @Bacco just wouldn’t need to if position were the DUPLICATE KEY in question. It would be good to confirm with the owner of the question before changing.

  • @Bacco Good, in this case then you can say that ON DUPLICATE KEY will run for the values of position that were violated, since in INSERT it does not specify the PRIMARY KEY. So yes, you can even edit the answer. Well remembered

  • @Bacco Ah, until they are didactic :)

Show 1 more comment

2

As ON DUPLICATE KEY does not allow conditional situations **, perhaps the best solution is a stored Procedure:

** but see an outline for this limit in the @Thomas response, which transfers the condition to within the parameters, which gives the same effect.


With stored Procedure, in PHP you do this:

$import = "CALL updateCustomizado( '$data[1]', '$data[2]', '$data[3]' );";

And in Mysql you create the database:

DELIMITER //
CREATE PROCEDURE `updateCustomizado`(xname VARCHAR(20), xposition INT, xprice DECIMAL)
BEGIN
   IF EXISTS (SELECT * FROM registros WHERE `position` = xposition) THEN
      UPDATE registros
      SET name=xname, price=xprice
      WHERE `position` = xposition AND status <> 1;
   ELSE
      INSERT INTO registros (name,position,price) VALUES ( xname, xposition, xprice);
   END IF;
END //
DELIMITER ;

I’m assuming that your key that fires the ON DUPLICATE KEY is the position, if it is not, just fit in the SELECT.

Remember to update the field types, I put only as an example.

  • Position is not my primary key, can you tell me how SELECT would look?

  • position is unique and gets a varchar. When I do SELECT name, position, price FROM records WHERE status = 0 INSERT into records(name,position,price)values('$data[1]','$data[2]','$data[3]') ON DUPLICATE KEY UPDATE position = position, name = '$data[1]', position = '$data[2]', price = '$data[3]', qty_try = 0 I get the error: You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'INSERT into records

  • I’ll try this trial tomorrow at work. Thanks for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.