如何编写MySQL if else endif语句?

时间:2022-03-27 15:43:35

I'd like a simple example of a MySQL if, else, endif statement.

我想要一个MySQL的简单示例if if else endif语句。

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

我想做这样的事情(在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
}

2 个解决方案

#1


8  

MySQL has INSERT ON DUPLICATE KEY UPDATE that allows you to update if the value already exist or Insert if not.

MySQL具有INSERT ON DUPLICATE KEY UPDATE,允许您更新值是否已存在或如果不存在则更新。

First you need to setup a UNIQUE Constraint,

首先,您需要设置UNIQUE约束,

ALTER TABLE myTable ADD CONSTRAINT tb_uq UNIQUE (ID)

that's it if you want ID to be unique. (This is just an example)

如果你想要ID是唯一的那就是它。 (这只是一个例子)

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

#2


4  

The if statement (in a stored block):

if语句(在存储块中):

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

Or the if function (in-line):

或if函数(内联):

IF(expr1,expr2,expr3)

which works as: IF( condition, what_to_do_if_true, what_to_do_if_false ) The last part being the same as an 'else'. An if-else-if would need to be embedded like:

其作用如下:IF(condition,what_to_do_if_true,what_to_do_if_false)最后一部分与'else'相同。 if-else-if需要嵌入,如:

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

Which would do the same as this in most programming languages:

在大多数编程语言中,这与此相同:

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

#1


8  

MySQL has INSERT ON DUPLICATE KEY UPDATE that allows you to update if the value already exist or Insert if not.

MySQL具有INSERT ON DUPLICATE KEY UPDATE,允许您更新值是否已存在或如果不存在则更新。

First you need to setup a UNIQUE Constraint,

首先,您需要设置UNIQUE约束,

ALTER TABLE myTable ADD CONSTRAINT tb_uq UNIQUE (ID)

that's it if you want ID to be unique. (This is just an example)

如果你想要ID是唯一的那就是它。 (这只是一个例子)

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

#2


4  

The if statement (in a stored block):

if语句(在存储块中):

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

Or the if function (in-line):

或if函数(内联):

IF(expr1,expr2,expr3)

which works as: IF( condition, what_to_do_if_true, what_to_do_if_false ) The last part being the same as an 'else'. An if-else-if would need to be embedded like:

其作用如下:IF(condition,what_to_do_if_true,what_to_do_if_false)最后一部分与'else'相同。 if-else-if需要嵌入,如:

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

Which would do the same as this in most programming languages:

在大多数编程语言中,这与此相同:

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