sqlÖÐcoalesceº¯ÊýÓ÷¨
sql ÖÐ coalesce º¯ÊýÓÃÓÚ´¦Àí null Öµ£¬½«±í´ïʽÁбíÖеĵÚÒ»¸ö·Ç null Öµ·µ»Ø£¬ÈôÊÇËùÓбí´ïʽ¶¼Îª null£¬Ôò·µ»ØĬÈÏÖµ¡£ËüÖ÷ÒªÓÃÓÚÌæ»» null Öµ¡¢ÌṩĬÈÏÖµºÍ¼¶Áª¼ì²é¡£ÈçÐèÌæ»» null Öµ£¬¿ÉʹÓà coalesce(expr1, expr2, …)¡£ÌṩĬÈÏÖµ£¬¿ÉʹÓà coalesce(expr1, expr2, …, default_value)¡£¼¶Áª¼ì²é£¬¿ÉʹÓà coalesce(expr1, expr2, …)¡£
SQL ÖÐ COALESCE º¯ÊýÓ÷¨
COALESCE º¯ÊýÊÇ SQL ÖÐÒ»¸ö³£Óõĺ¯Êý£¬ÓÃÓÚ´¦Àí NULL Öµ¡£Ëü¿ÉÒÔ½«¶à¸ö±í´ïʽ×÷Ϊһ¸ö²ÎÊýÁÐ±í£¬²¢·µ»ØµÚÒ»¸ö·Ç NULL Öµ¡£ÈôÊÇËùÓбí´ïʽ¶¼Îª NULL£¬Ôò·µ»ØĬÈÏÖµ¡£
Óï·¨
COALESCE(expr1, expr2, …, exprN, default_value)
ÆäÖУº
expr1, expr2, …, exprN£ºÒª¼ì²éµÄ±í´ïʽ¡£
default_value£ºÈôÊÇËùÓбí´ïʽ¶¼Îª NULL£¬Ôò·µ»ØµÄĬÈÏÖµ£¨¿ÉÑ¡£©¡£
Ó÷¨
COALESCE º¯ÊýÖ÷ÒªÓÃÓÚ´¦ÀíÒÔϳ¡¾°£º
Ìæ»» NULL Öµ£ºCOALESCE º¯Êý¿ÉÒÔ½« NULL ÖµÌ滻ΪÆäËû·Ç NULL Öµ£¬´Ó¶øÈ·±£Êý¾ÝÍêÕûÐÔ¡£
ÌṩĬÈÏÖµ£ºµ±Ã»ÓпÉÓÃÊý¾Ýʱ£¬COALESCE º¯Êý¿ÉÒÔÌṩһ¸öĬÈÏÖµ£¬ÒÔ±ÜÃâ¹ýʧ»òÒâÍâЧ¹û¡£
¼¶Áª¼ì²é£ºCOALESCE º¯Êý¿ÉÒÔ¼¶Áª¼ì²é¶à¸ö±í´ïʽ£¬Ö±µ½ÕÒµ½Ò»¸ö·Ç NULL Öµ¡£
ʾÀý
1. Ìæ»» NULL Öµ
SELECT COALESCE(name, 'Unknown') FROM users;
µÇ¼ºó¸´ÖÆ
Õâ»á½« name ÁÐÖеÄËùÓÐ NULL ÖµÌ滻Ϊ×Ö·û´® “Unknown”¡£
2. ÌṩĬÈÏÖµ
SELECT COALESCE(age, 0) FROM users;
µÇ¼ºó¸´ÖÆ
Õâ»áÔÚ age ÁÐÖн«ËùÓÐ NULL ÖµÌ滻ΪÊý×Ö 0¡£
3. ¼¶Áª¼ì²é
SELECT COALESCE(address, city, country) FROM users;
µÇ¼ºó¸´ÖÆ
Õâ»áÊ×Ïȼì²é address ÁÐÖеÄÖµ¡£ÈôÊÇ address Ϊ NULL£¬Ëü»á¼ì²é city ÁеÄÖµ¡£ÈôÊÇ city ҲΪ NULL£¬Ôò·µ»Ø country ÁеÄÖµ¡£
×¢ÖØÊÂÏî
COALESCE º¯Êý²»½ÓÊÜ¿Õ²ÎÊýÁÐ±í¡£
COALESCE º¯Êý·µ»ØµÚÒ»¸ö·Ç NULL Öµ£¬¶ø²»ÊDZí´ïʽÁбíÖÐËùÓÐ·Ç NULL ÖµµÄÁÐ±í¡£
ÈôÊÇËùÓбí´ïʽ¶¼Îª NULL ÇÒûÓÐÌṩ default_value£¬Ôò COALESCE º¯Êý·µ»Ø NULL¡£
ÒÔÉϾÍÊÇsqlÖÐcoalesceº¯ÊýÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡