Create OR Update - MySQL

0

Is there something 'native' to MYSQL that does an Update OR Create?

Something that is more performative than SELECT, validation, and INSERT / UPDATE as usual.

I do not mean methods that simplify this via application, my doubt is about this action under the responsibility of the database itself.

Example of how to use it in Laravel:

App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

However, this is only an abstraction of SELECT and condition.

In MongoDB, we have this:

Person.update(
  { name : 'TED' },
  { name : 'TED', age : 50 },
  { upsert : true }
,callback );

The upsert parameter causes update or create to work.

    
asked by anonymous 29.03.2018 / 19:41

2 answers

1

If you have a primary key or a unique index, you can use the ON DUPLICATE KEY event, it would look something like this:

INSERT INTO 'sua_tabela' ('campo1', 'campo2')
VALUES ('informação1', 'informação2')
ON DUPLICATE KEY UPDATE 'campo1' = 'informação1', 'campo2' = 'informação2';

See more here .

    
29.03.2018 / 19:53
1

Good afternoon, there is, REPLACE native MySQL.

You can use this way: REPALCE INTO table...

If there is a record it updates the fields, if it does not exist it inserts into your table.

Ref: link

    
29.03.2018 / 19:51