Use case when for string replacement
Copy codeThe Code is as follows: mysql> select * from sales;
9 rows in set (0.01 sec)
SELECT name AS Name,
CASE category
WHEN "Holiday" THEN "Seasonal"
WHEN "Sion" THEN "Bi_annual"
WHEN "Literary" THEN "Random" end as "Pattern"
FROM sales;
9 rows in set (0.00 sec)
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)
) ENGINE = MyISAM;
Insert into sales value (1, 'java ', 1067,200,150,267, 'holiday ');
Insert into sales value (2, 'C', 970,770,531,486, 'sale sion ');
Insert into sales value (3, 'javascript ', 21,856, 'litery ');
Insert into sales value (4, 'SQL', 782,357,168,250, 'analysion ');
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, 'plusion ');
Simple statement
Copy codeThe Code is as follows:
Select case when 10*2 = 30 THEN '30 correct'
WHEN 10*2 = 40 THEN '40 correct'
ELSE 'should be 10*2 = 20'
End as 'result ';
Multiple Expressions
Copy codeThe Code is as follows: select case 10*2
WHEN 20 THEN '20 correct'
WHEN 30 THEN '30 correct'
WHEN 40 THEN '40 correct'
ELSE 'no results'
End as 'result ';
Use case when in SELECT query
Copy codeThe Code is as follows: 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' No one 17 and under .'
WHEN 'nr 'then' Use discretion when processing ing .'
ELSE 'OK to rent to minors .'
End as Policy
FROM DVDs
Order by Name;
8 rows in set (0.01 sec)