Mysql Update and insert in a single query

0

How can I write a Query to update certain fields where the only thing I want to check is the IDKey, but if it does not find the IDKey, the record does not exist, make an Insert of the record using this same information

what I have:

str="UPDATE Det_Info SET Size=1, Color=1 WHERE KeyProduc='0100';
OR
INSERT INTO Det_Info(KeyProduc,Size,Color) VALUES ('0100',1,1);"

The idea is to do it in a single query, and not wait for the resolution of one query to make another, and the priority is to do the Update. without stored procedures.

    
asked by Francisco Núñez 28.10.2017 в 16:58
source

2 answers

0

You should use a SELECT to check if the KeyProduc exists

Example:

SELECT COUNT(KeyProduc) FROM Det_Info WHERE KeyProduc='0100';

If the result of that count is zero, you make the INSERT ; otherwise, you execute UPDATE .

    
answered by 28.10.2017 в 17:20
0

You make an insert, and you add the condition of if you found a duplicate value, this clear taking into account that your column KeyProduc is unique, which should be it

INSERT INTO Det_Info (KeyProduc,Size,Color) VALUES ('0100', 3,2)
ON DUPLICATE KEY UPDATE Size = 1, Color = 1;
    
answered by 28.10.2017 в 17:26