您的位置:首页 > 数据库 > MySQL

MySQL的if,case语句使用总结

2015-05-09 11:50 627 查看
示例数据库

/*
mysql> SELECT Name, RatingID AS Rating,
->    CASE RatingID
->       WHEN 'R' THEN 'Under 17 requires an adult.'
->       WHEN 'X' THEN 'No one 17 and under.'
->       WHEN 'NR' THEN 'Use discretion when renting.'
->       ELSE 'OK to rent to minors.'
->    END AS Policy
-> FROM DVDs
-> ORDER BY Name;
+-----------+--------+------------------------------+
| Name      | Rating | Policy                       |
+-----------+--------+------------------------------+
| Africa    | PG     | OK to rent to minors.        |
| Amadeus   | PG     | OK to rent to minors.        |
| Christmas | NR     | Use discretion when renting. |
| Doc       | G      | OK to rent to minors.        |
| Falcon    | NR     | Use discretion when renting. |
| Mash      | R      | Under 17 requires an adult.  |
| Show      | NR     | Use discretion when renting. |
| View      | NR     | Use discretion when renting. |
+-----------+--------+------------------------------+
8 rows in set (0.01 sec)

*/

Drop table DVDs;

CREATE TABLE DVDs (
ID SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(60) NOT NULL,
NumDisks TINYINT NOT NULL DEFAULT 1,
RatingID VARCHAR(4) NOT NULL,
StatID CHAR(3) NOT NULL
)
ENGINE=INNODB;

INSERT INTO DVDs (Name, NumDisks, RatingID, StatID)
VALUES ('Christmas', 1, 'NR', 's1'),
('Doc',       1, 'G',  's2'),
('Africa',    1, 'PG', 's1'),
('Falcon',    1, 'NR', 's2'),
('Amadeus',   1, 'PG', 's2'),
('Show',      2, 'NR', 's2'),
('View',      1, 'NR', 's1'),
('Mash',      2, 'R',  's2');

SELECT Name, RatingID AS Rating,
CASE RatingID
WHEN 'R' THEN 'Under 17 requires an adult.'
WHEN 'X' THEN 'No one 17 and under.'
WHEN 'NR' THEN 'Use discretion when renting.'
ELSE 'OK to rent to minors.'
END AS Policy
FROM DVDs
ORDER BY Name;


代码

IFNULL(expr1,expr2)

假如expr1 不为 NULL,则 IFNULL() 的返回值为 expr1; 否则其返回值为 expr2。IFNULL()的返回值是数字或是字符串

IF ELSE 做为流程控制语句使用

if实现条件判断,满足不同条件执行不同的操作

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

注意:IF作为一条语句,在END IF后需要加上分号“;”以表示语句结束,其他语句如CASE、LOOP等也是相同的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: