Article Directory
foreword
There are many ways to realize the judgment function in the Mysql database, which are divided into functions and if statements. The advantage of functions is that they can be run as part of SQL, while if statements need to be used in stored procedures.
One, ifnull function
grammar:
IFNULL(expression, alt_value)
explain:
Determine whether the first expression is NULL, if it is NULL, return the value of the second parameter, if it is not NULL, return the value of the first parameter
Parameter Description:
Expression:必须,要测试的值
alt_value:必须,expression 表达式为 NULL 时返回的值。
Common examples:
expression_1 parameter is empty, returns a
SELECT IFNULL(NULL, 'a');
expression_1 parameter is not empty, return 1
SELECT IFNULL(1, 'a');
An empty string also indicates a value, return an empty string
SELECT IFNULL('', 'a');
0 also means there is a value, return 0
SELECT IFNULL(0, 'a');
Second, the nullif function
grammar:
NULLIF(expression1, expression2)
explain:
The NULLIF() function is used to compare two expressions. If two expressions are equal, NULLIF() function will return NULL otherwise it will return the first expression.
Common examples:
If the two expressions are equal, return null
SELECT NULLIF('abc', 'abc');
Two expressions are not equal, return the first expression abc
SELECT NULLIF('abc', 'abcd');
Three, if function
grammar:
IF(expr1,expr2,expr3)
explain:
If the expression expr1=true(expr1 <> 0 and expr1 <> NULL), return expr2, otherwise return expr3, the return value of IF() is a numeric value or a string value, depending on the context.
Common examples:
The expr1 parameter is 1, the result is true, and the return is correct
select if(1,'正确','错误');
Four, if statement (used for stored procedures)
grammar:
IF expression THEN
statements;
END IF;
explain:
If the expression evaluates to TRUE, the statement will be executed, otherwise, control will be passed to the next statement that follows.
Five, if-else statement (used for stored procedures)
grammar:
IF expression THEN
statements;
ELSE
else-statements;
END IF;
explain:
If the expression evaluates to TRUE, the statements statement will be executed, otherwise, the else-statements statement will be executed.
Six, if-elseif-else statement (used for stored procedures)
grammar:
IF expression THEN
statements;
ELSEIF elseif-expression THEN
elseif-statements;
...
ELSE
else-statements;
END IF;
explain:
If the expression (expression) evaluates to TRUE, the statements (statements) in the IF branch will be executed; if the expression evaluates to FALSE, then if elseif_expression evaluates to TRUE, MySQL will execute elseif-expression, otherwise execute ELSE else-statements in a branch.
Summarize
Word document download address: mysql implements six usage forms of if statement judgment function