程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> mysql when case 條件判斷語名用法

mysql when case 條件判斷語名用法

編輯:MySQL綜合教程

一個CASE表達式的默認返回值類型是任何返回值的相容集合類型,但具體情況視其所在語境而定。如果用在字符串語境中,則返回結果味字符串。如果用在數字語境中,則返回結果為十進制值、實值或整數值

語法

 代碼如下 復制代碼

CASE value WHEN [compare-value] THEN result [WHEN [compare-value] THEN result ...] [ELSE result] END CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END

實例

 代碼如下 復制代碼

SELECT CASE WHEN 10*2=30 THEN '30 correct'
WHEN 10*2=40 THEN '40 correct'
ELSE 'Should be 10*2=20'
END;

復雜點

 

 代碼如下 復制代碼 SELECT CASE 10*2
WHEN 20 THEN '20 correct'
WHEN 30 THEN '30 correct'
WHEN 40 THEN '40 correct'
END;

實例

 

 代碼如下 復制代碼 /*
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;

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved