程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> MySQL 的CASE WHEN 語句應用解釋

MySQL 的CASE WHEN 語句應用解釋

編輯:MySQL綜合教程

MySQL 的CASE WHEN 語句應用解釋。本站提示廣大學習愛好者:(MySQL 的CASE WHEN 語句應用解釋)文章只能為提供參考,不一定能成為您想要的結果。以下是MySQL 的CASE WHEN 語句應用解釋正文


mysql數據庫中CASE WHEN語句。

case when語句,用於盤算前提列表並前往多個能夠成果表達式之一。

CASE 具有兩種格局:

簡略 CASE 函數將某個表達式與一組簡略表達式停止比擬以肯定成果。

CASE 搜刮函數盤算一組布爾表達式以肯定成果。
兩種格局都支撐可選的 ELSE 參數。

語法
簡略 CASE 函數:


CASE input_expression
    WHEN when_expression THEN result_expression
        [ ...n ]
    [
        ELSE else_result_expression
    END

CASE 搜刮函數:


CASE   
WHEN Boolean_expression THEN result_expression
        [ ...n ]
    [
        ELSE else_result_expression
    END

參數
input_expression

是應用簡略 CASE 格局時所盤算的表達式。Input_expression 是任何有用的 Microsoft? SQL Server? 表達式。

WHEN when_expression

應用簡略 CASE 格局時 input_expression 所比擬的簡略表達式。When_expression 是隨意率性有用的 SQL Server 表達式。Input_expression 和每一個 when_expression 的數據類型必需雷同,或許是隱性轉換。

占位符,注解可使用多個 WHEN when_expression THEN result_expression 子句或 WHEN Boolean_expression THEN result_expression 子句。

THEN result_expression

當 input_expression = when_expression 取值為 TRUE,或許 Boolean_expression 取值為 TRUE 時前往的表達式。
result expression 是隨意率性有用的 SQL Server 表達式。

ELSE else_result_expression

當比擬運算取值不為 TRUE 時前往的表達式。假如省略此參數而且比擬運算取值不為 TRUE,CASE 將前往 NULL 值。Else_result_expression 是隨意率性有用的 SQL Server 表達式。Else_result_expression 和一切 result_expression 的數據類型必需雷同,或許必需是隱性轉換。

WHEN Boolean_expression

應用 CASE 搜刮格局時所盤算的布爾表達式。Boolean_expression 是隨意率性有用的布爾表達式。

成果類型

從 result_expressions 和可選 else_result_expression 的類型聚集中前往最高的優先規矩類型。有關更多信息,請拜見數據類型的優先次序。

成果值

簡略 CASE 函數:
盤算 input_expression,然後按指定次序對每一個 WHEN 子句的 input_expression = when_expression 停止盤算。

前往第一個取值為 TRUE 的 (input_expression = when_expression) 的 result_expression。

假如沒有取值為 TRUE 的 input_expression = when_expression,則當指定 ELSE 子句時 SQL Server 將前往 else_result_expression;若沒有指定 ELSE 子句,則前往 NULL 值。
CASE 搜刮函數:
按指定次序為每一個 WHEN 子句的 Boolean_expression 求值。

前往第一個取值為 TRUE 的 Boolean_expression 的 result_expression。

假如沒有取值為 TRUE 的 Boolean_expression,則當指定 ELSE 子句時 SQL Server 將前往 else_result_expression;若沒有指定 ELSE 子句,則前往 NULL 值。

上面分享一些mysql case when語句的例子。

A. 應用帶有簡略 CASE 函數的 SELECT 語句
在 SELECT 語句中,簡略 CASE 函數僅檢討能否相等,而不停止其它比擬。

例子,應用 CASE 函數更改圖書分類顯示。


USE pubs
GO
SELECT      Category =
         CASE type
            WHEN 'popular_comp' THEN 'Popular Computing'
            WHEN 'mod_cook' THEN 'Modern Cooking'
            WHEN 'business' THEN 'Business'
            WHEN 'psychology' THEN 'Psychology'
            WHEN 'trad_cook' THEN 'Traditional Cooking'
            ELSE 'Not yet categorized'
         END,
      CAST(title AS varchar(25)) AS 'Shortened Title',
      price AS Price
FROM titles
WHERE price IS NOT NULL
ORDER BY type, price
COMPUTE AVG(price) BY type
GO

正文,後來我試了一下不讓用category=。

我應用的代碼為:
 


SELECT 
  case gender
 WHEN 1 THEN 'NAN'
 WHEN 0 THEN 'NV'
end  as gender
FROM
t_swidy_day_nutrient

成果集:
 

Category               Shortened Title              Price                        
------------------- ------------------------- --------------------------
Business               You Can Combat Computer S 2.99                         
Business               Cooking with Computers: S 11.95                        
Business               The Busy Executive's Data 19.99                        
Business               Straight Talk About Compu 19.99                   

                                                 avg
                                                 ==========================
                                                 13.73                   

Category               Shortened Title              Price                        
------------------- ------------------------- --------------------------
Modern Cooking         The Gourmet Microwave        2.99                         
Modern Cooking         Silicon Valley Gastronomi 19.99                   

                                                 avg
                                                 ==========================
                                                 11.49                   

Category               Shortened Title              Price                        
------------------- ------------------------- --------------------------
Popular Computing      Secrets of Silicon Valley 20.00                        
Popular Computing      But Is It User Friendly?  22.95                   

                                                 avg
                                                 ==========================
                                                 21.48                   

Category               Shortened Title              Price                        
------------------- ------------------------- --------------------------
Psychology             Life Without Fear            7.00                         
Psychology             Emotional Security: A New 7.99                         
Psychology             Is Anger the Enemy?          10.95                        
Psychology             Prolonged Data Deprivatio 19.99                        
Psychology             Computer Phobic AND Non-P 21.59                   

                                                 avg
                                                 ==========================
                                                 13.50                   

Category               Shortened Title              Price                        
------------------- ------------------------- --------------------------
Traditional Cooking Fifty Years in Buckingham 11.95                        
Traditional Cooking Sushi, Anyone?               14.99                        
Traditional Cooking Onions, Leeks, and Garlic 20.95                   

                                                 avg
                                                 ==========================
                                                 15.96                   

(21 row(s) affected)

B. 應用帶有簡略 CASE 函數和 CASE 搜刮函數的

 SELECT 語句
在 SELECT 語句中,CASE 搜刮函數許可依據比擬值在成果集內對值停止調換。

例子:依據圖書的價錢規模將價錢(money 列)顯示為文本正文。
 


USE pubs
GO
SELECT       'Price Category' =
         CASE
            WHEN price IS NULL THEN 'Not yet priced'
            WHEN price < 10 THEN 'Very Reasonable Title'
            WHEN price >= 10 and price < 20 THEN 'Coffee Table Title'
            ELSE 'Expensive book!'
         END,
      CAST(title AS varchar(20)) AS 'Shortened Title'
FROM titles
ORDER BY price
GO

成果集:
 

Price Category           Shortened Title        
--------------------- --------------------
Not yet priced           Net Etiquette          
Not yet priced           The Psychology of Co
Very Reasonable Title The Gourmet Microwav
Very Reasonable Title You Can Combat Compu
Very Reasonable Title Life Without Fear      
Very Reasonable Title Emotional Security: 
Coffee Table Title       Is Anger the Enemy? 
Coffee Table Title       Cooking with Compute
Coffee Table Title       Fifty Years in Bucki
Coffee Table Title       Sushi, Anyone?         
Coffee Table Title       Prolonged Data Depri
Coffee Table Title       Silicon Valley Gastr
Coffee Table Title       Straight Talk About 
Coffee Table Title       The Busy Executive's
Expensive book!          Secrets of Silicon V
Expensive book!          Onions, Leeks, and G
Expensive book!          Computer Phobic And 
Expensive book!          But Is It User Frien

(18 row(s) affected)

C. 應用帶有 SUBSTRING 和 SELECT 的 CASE 函數

例子,應用 CASE 和 THEN 生成一個有關作者、圖書標識號和每一個作者所著圖書類型的列表。
 


USE pubs
SELECT SUBSTRING((RTRIM(a.au_fname) + ' '+
      RTRIM(a.au_lname) + ' '), 1, 25) AS Name, a.au_id, ta.title_id,
      Type =
  CASE
       WHEN SUBSTRING(ta.title_id, 1, 2) = 'BU' THEN 'Business'
       WHEN SUBSTRING(ta.title_id, 1, 2) = 'MC' THEN 'Modern Cooking'
       WHEN SUBSTRING(ta.title_id, 1, 2) = 'PC' THEN 'Popular Computing'
       WHEN SUBSTRING(ta.title_id, 1, 2) = 'PS' THEN 'Psychology'
       WHEN SUBSTRING(ta.title_id, 1, 2) = 'TC' THEN 'Traditional Cooking'
  END
FROM titleauthor ta JOIN authors a ON ta.au_id = a.au_id

成果集:
 

Name                         au_id          title_id Type                  
------------------------- ----------- -------- -------------------
Johnson White                172-32-1176 PS3333      Psychology            
Marjorie Green               213-46-8915 BU1032      Business              
Marjorie Green               213-46-8915 BU2075      Business              
Cheryl Carson                238-95-7766 PC1035      Popular Computing     
Michael O'Leary              267-41-2394 BU1111      Business              
Michael O'Leary              267-41-2394 TC7777      Traditional Cooking
Dean Straight                274-80-9391 BU7832      Business              
Abraham Bennet               409-56-7008 BU1032      Business              
Ann Dull                     427-17-2319 PC8888      Popular Computing     
Burt Gringlesby              472-27-2349 TC7777      Traditional Cooking
Charlene Locksley            486-29-1786 PC9999      Popular Computing     
Charlene Locksley            486-29-1786 PS7777      Psychology            
Reginald Blotchet-Halls      648-92-1872 TC4203      Traditional Cooking
Akiko Yokomoto               672-71-3249 TC7777      Traditional Cooking
Innes del Castillo           712-45-1867 MC2222      Modern Cooking        
Michel DeFrance              722-51-5454 MC3021      Modern Cooking        
Stearns MacFeather           724-80-9391 BU1111      Business              
Stearns MacFeather           724-80-9391 PS1372      Psychology            
Livia Karsen                 756-30-7391 PS1372      Psychology            
Sylvia Panteley              807-91-6654 TC3218      Traditional Cooking
Sheryl Hunter                846-92-7186 PC8888      Popular Computing     
Anne Ringer                  899-46-2035 MC3021      Modern Cooking        
Anne Ringer                  899-46-2035 PS2091      Psychology            
Albert Ringer                998-72-3567 PS2091      Psychology            
Albert Ringer                998-72-3567 PS2106      Psychology 
(25 row(s) affected)

CASE 能夠是 SQL 中被誤用最多的症結字之一。
固然,能夠之前用過這個症結字來創立字段,然則它還具有更多用法。

例如,可以在 WHERE 子句中應用 CASE。

起首,來看下 CASE 的語法。在普通的 SELECT 中,其語法以下:


SELECT <myColumnSpec> =
CASE
WHEN <A> THEN <somethingA>
WHEN <B> THEN <somethingB>
ELSE <somethingE>
END

以上代碼,須要器具體的參數取代尖括號中的內容。

例子:


USE pubs
GO
SELECT
    Title,
    'Price Range' =
    CASE
        WHEN price IS NULL THEN 'Unpriced'
        WHEN price < 10 THEN 'Bargain'
        WHEN price BETWEEN 10 and 20 THEN 'Average'
        ELSE 'Gift to impress relatives'
    END
FROM titles
ORDER BY price
GO

這是 CASE 的典范用法,然則應用 CASE 其實可以做更多的工作。

比喻說上面的 GROUP BY 子句中的 CASE:


SELECT 'Number of Titles', Count(*)
FROM titles
GROUP BY
    CASE
        WHEN price IS NULL THEN 'Unpriced'
        WHEN price < 10 THEN 'Bargain'
        WHEN price BETWEEN 10 and 20 THEN 'Average'
        ELSE 'Gift to impress relatives'
    END
GO

乃至還可以組合這些選項,添加一個 ORDER BY 子句,例如:
 


USE pubs
GO
SELECT
    CASE
        WHEN price IS NULL THEN 'Unpriced'
        WHEN price < 10 THEN 'Bargain'
        WHEN price BETWEEN 10 and 20 THEN 'Average'
        ELSE 'Gift to impress relatives'
    END AS Range,
    Title
FROM titles
GROUP BY
    CASE
        WHEN price IS NULL THEN 'Unpriced'
        WHEN price < 10 THEN 'Bargain'
        WHEN price BETWEEN 10 and 20 THEN 'Average'
        ELSE 'Gift to impress relatives'
    END,
    Title
ORDER BY
    CASE
        WHEN price IS NULL THEN 'Unpriced'
        WHEN price < 10 THEN 'Bargain'
        WHEN price BETWEEN 10 and 20 THEN 'Average'
        ELSE 'Gift to impress relatives'
    END,
    Title
GO

留意,為了在 GROUP BY 塊中應用 CASE,查詢語句須要在 GROUP BY 塊中反復 SELECT 塊中的 CASE 塊。

除選擇自界說字段以外,在許多情形下 CASE 都異常有效。

略加深刻,還可以獲得之前以為弗成能獲得的分組排序成果集。

應用CASE WHEN停止字符串調換處置

/*
 mysql> select * from sales;
 +-----+------------+--------+--------+--------+------+------------+
 | num | name       | winter | spring | summer | fall | category   |
 +-----+------------+--------+--------+--------+------+------------+
 |   1 | Java       |   1067 |    200 |    150 |  267 | Holiday    |
 |   2 | C          |    970 |    770 |    531 |  486 | Profession |
 |   3 | JavaScript |     53 |     13 |     21 |  856 | Literary   |
 |   4 | SQL        |    782 |    357 |    168 |  250 | Profession |
 |   5 | Oracle     |    589 |    795 |    367 |  284 | Holiday    |
 |   6 | MySQL      |    953 |    582 |    336 |  489 | Literary   |
 |   7 | Cplus      |    752 |    657 |    259 |  478 | Literary   |
 |   8 | Python     |     67 |     23 |     83 |  543 | Holiday    |
 |   9 | PHP        |    673 |     48 |    625 |   52 | Profession |
 +-----+------------+--------+--------+--------+------+------------+
 9 rows in set (0.01 sec)
 mysql> SELECT name AS Name,
     -> CASE category
     -> WHEN "Holiday" THEN "Seasonal"
     -> WHEN "Profession" THEN "Bi_annual"
     -> WHEN "Literary" THEN "Random" END AS "Pattern"
     -> FROM sales;
 +------------+-----------+
 | Name       | Pattern   |
 +------------+-----------+
 | Java       | Seasonal  |
 | C          | Bi_annual |
 | JavaScript | Random    |
 | SQL        | Bi_annual |
 | Oracle     | Seasonal  |
 | MySQL      | Random    |
 | Cplus      | Random    |
 | Python     | Seasonal  |
 | PHP        | Bi_annual |
 +------------+-----------+
 9 rows in set (0.00 sec)
 */
 Drop table sales;
 CREATE TABLE sales(
     num MEDIUMINT NOT NULL AUTO_INCREMENT,
     name CHAR(20),
     winter INT,
     spring INT,
     summer INT,
     fall INT,
     category CHAR(13),
     primary key(num)
 )type=MyISAM;
 insert into sales value(1, 'Java', 1067 , 200, 150, 267,'Holiday');
 insert into sales value(2, 'C',970,770,531,486,'Profession');
 insert into sales value(3, 'JavaScript',53,13,21,856,'Literary');
 insert into sales value(4, 'SQL',782,357,168,250,'Profession');
 insert into sales value(5, 'Oracle',589,795,367,284,'Holiday');
 insert into sales value(6, 'MySQL',953,582,336,489,'Literary');
 insert into sales value(7, 'Cplus',752,657,259,478,'Literary');
 insert into sales value(8, 'Python',67,23,83,543,'Holiday');
 insert into sales value(9, 'PHP',673,48,625,52,'Profession');
 select * from sales;
 SELECT name AS Name,
 CASE category
 WHEN "Holiday" THEN "Seasonal"
 WHEN "Profession" THEN "Bi_annual"
 WHEN "Literary" THEN "Random" END AS "Pattern"
 FROM sales;

簡略語句

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;

在SELECT查詢中應用CASE WHEN

/*
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