jeudi 4 mai 2017

Insert only if statements are true - MySql

I want to build query which inserts row to table only if statement is true. Well in my mind it should go like this (this is the easiest way - spliting it into multiple queries):

if((SELECT COUNT(*) FROM my_table WHERE value1 = x)>0){
//response: already inserted
}else if((SELECT COUNT(*) FROM my_table WHERE value2 = x AND value3 = true)>0){ //checking for very very other specific case 
//response: another error response - to tell user why action is wrong
}else{
INSERT INTO my_table value1, value2 ...
//response: ok
}

The easiest way is to split this into multiple queries and then use this algorithm, but I want to make it single query, because I think the less rounds between connecting to db, querying, getting and fetching response etc. is much more efficient.

I was thinking about throwing custom mysql codes when statements are false, but I have no idea how the query itself should look like.

Thank you for any help.

Aucun commentaire:

Enregistrer un commentaire