How to write MySQL expression if else endif?

I need a simple example MySQL statement if, else, endif.

I want to do something like this (in Java):

SELECT COUNT(*) FROM  `table` WHERE  `userID` =  1

if(count == 0){
  INSERT INTO  `table` (`userID`,`A` ,`B`)VALUES ('1',  '323',  '232')
}
else{
  UPDATE  `table` SET  `A` =  '323', `B` =  '232' WHERE  `userID` =1
}
+5
source share
2 answers

MySQL has INSERT ON DUPLICATE KEY UPDATE, which allows you to update if a value already exists or insert if not.

First you need to set a limit UNIQUE,

ALTER TABLE myTable ADD CONSTRAINT tb_uq UNIQUE (ID)

to have it if you want it to IDbe unique. (This is just an example)

INSERT INTO tableName(userID, A, B) 
VALUES (1, 323, 232)
ON DUPLICATE KEY
UPDATE  A = 323,
        B = 232
+8
source

The if statement (in a saved block):

IF search_condition THEN statement_list
    [ELSEIF search_condition THEN statement_list] ...
    [ELSE statement_list]
END IF

Or the if function (in line):

IF(expr1,expr2,expr3)

: IF (, what_to_do_if_true, what_to_do_if_false) "else". if-else-if :

SELECT IF( id==1, "1", IF( ID==2, "2", "Neither" );

, :

if( id == 1 ) {
    print "1"
} elsif( id == 2 ) {
    print "2"
} else {
    print "Neither"
}
+4

All Articles