sqlÖеÄcaseÓï¾äÓ÷¨
case Óï¾äÓÃÓÚƾ֤Ìõ¼þ·µ»Ø²î±ðÖµ¡£Óï·¨£ºcase when condition then result when condition then result … else default_result end¡£Ó÷¨£º1. Ö¸¶¨Ìõ¼þ£»2. ·µ»ØÌõ¼þΪÕæµÄЧ¹û£»3. ʹÓà else ×Ó¾äÖ¸¶¨ËùÓÐÌõ¼þ¶¼Îª¼ÙʱµÄĬÈÏЧ¹û¡£
SQL ÖÐµÄ CASE Óï¾äÓ÷¨
CASE Óï¾äÔÚ SQL ÖÐÓÃÓÚƾ֤²î±ðµÄÌõ¼þ·µ»Ø²î±ðµÄÖµ¡£ËüµÄÓï·¨ÈçÏ£º
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE default_result END
µÇ¼ºó¸´ÖÆ
Ó÷¨£º
Ö¸¶¨Ìõ¼þ£ºÊ¹Óà WHEN ×Ó¾äÖ¸¶¨Òª¼ì²éµÄÌõ¼þ¡£
·µ»ØЧ¹û£ºÈôÊÇÌõ¼þΪÕ棬Ôò·µ»Ø¹ØÁªµÄ result Öµ¡£
ĬÈÏЧ¹û£ºÊ¹Óà ELSE ×Ó¾äÖ¸¶¨ÈôÊÇËùÓÐÌõ¼þ¾ùΪ¼ÙʱҪ·µ»ØµÄÖµ¡£
ʾÀý£º
-- ƾ֤·ÖÊýÅÌËãЧ¹ûÆ·¼¶ SELECT CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' WHEN score >= 70 THEN 'C' WHEN score >= 60 THEN 'D' ELSE 'F' END AS grade FROM students;
µÇ¼ºó¸´ÖÆ
¸ü¶àÑ¡Ï
¶à¸ö CASE Óï¾ä£º¿ÉÒÔʹÓÃǶÌ× CASE Óï¾äÀ´´¦Àí¸üÖØ´óµÄÇéÐΡ£
SEARCH Ìõ¼þ£ºÊ¹Óà SEARCH ×Ó¾äÔÚ×Ö·û´®ÖÐËÑË÷ģʽ²¢·µ»ØÆ¥ÅäÏî¡£
NULLIF Ìõ¼þ£ºÊ¹Óà NULLIF ×Ó¾ä¼ì²éÖµÊÇ·ñΪ NULL£¬ÈôÊÇÊÇÔò·µ»ØÒ»¸öÖ¸¶¨µÄ NULL Öµ¡£
ÓÅÊÆ£º
ÌṩһÖÖ¾«Á·µÄ·½·¨À´´¦Àí²î±ðÌõ¼þ¡£
Ìá¸ßÅÌÎʵĿɶÁÐԺͿÉά»¤ÐÔ¡£
Ïû³ý¶Ô IF-ELSE Óï¾äµÄÐèÒª¡£
×¢ÖØÊÂÏ
±ØÐèÖ¸¶¨ ELSE ×Ó¾äÒÔÈ·±£·µ»ØÒ»¸öÖµ¡£
WHEN ×Ó¾äµÄÌõ¼þ±ØÐèÊÇ»¥³âµÄ¡£
ÒÔÉϾÍÊÇsqlÖеÄcaseÓï¾äÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡