mysql when case 条件判断语名用法
2019/10/10/17:32:58 阅读:1895 来源:谷歌SEO算法 标签:
1号店SEO
一个CASE表达式的默认返回值类型是任何返回值的相容集合类型,但具体情况视其所在语境而定,如果用在字符串语境中,则返回结果味字符串,如果用在数字语境中,则返回结果为十进制值、实值或整数值.
语法,代码如下:
- CASEvalueWHEN[compare-value]THENresult[WHEN[compare-value]THENresult...][ELSEresult]ENDCASEWHEN[condition]THENresult[WHEN[condition]THENresult...][ELSEresult]END
实例,代码如下:
- SELECTCASEWHEN10*2=30THEN'30correct'
- WHEN10*2=40THEN'40correct'
- ELSE'Shouldbe10*2=20'
- END;
复杂点,代码如下:
- SELECTCASE10*2
- WHEN20THEN'20correct'
- WHEN30THEN'30correct'
- WHEN40THEN'40correct'
- END;
实例,代码如下:
- /*
- mysql>SELECTName,RatingIDASRating,
- ->CASERatingID
- ->WHEN'R'THEN'Under17requiresanadult.'
- ->WHEN'X'THEN'Noone17andunder.'
- ->WHEN'NR'THEN'Usediscretionwhenrenting.'
- ->ELSE'OKtorenttominors.'
- ->ENDASPolicy
- ->FROMDVDs
- ->ORDERBYName;
- +-----------+--------+------------------------------+
- |Name|Rating|Policy|
- +-----------+--------+------------------------------+
- |Africa|PG|OKtorenttominors.|
- |Amadeus|PG|OKtorenttominors.|
- |Christmas|NR|Usediscretionwhenrenting.|
- |Doc|G|OKtorenttominors.|
- |Falcon|NR|Usediscretionwhenrenting.|
- |Mash|R|Under17requiresanadult.|
- |Show|NR|Usediscretionwhenrenting.|
- |View|NR|Usediscretionwhenrenting.|
- +-----------+--------+------------------------------+
- 8rowsinset(0.01sec)
- */
- DroptableDVDs;
- CREATETABLEDVDs(
- IDSMALLINTNOTNULLAUTO_INCREMENTPRIMARYKEY,
- NameVARCHAR(60)NOTNULL,
- NumDisksTINYINTNOTNULLDEFAULT1,
- RatingIDVARCHAR(4)NOTNULL,
- StatIDCHAR(3)NOTNULL
- )
- ENGINE=INNODB;
- INSERTINTODVDs(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');
- SELECTName,RatingIDASRating,
- CASERatingID
- WHEN'R'THEN'Under17requiresanadult.'
- WHEN'X'THEN'Noone17andunder.'
- WHEN'NR'THEN'Usediscretionwhenrenting.'
- ELSE'OKtorenttominors.'--phpfensi.com
- ENDASPolicy
- FROMDVDs
- ORDERBYName;
热门评论