order byÔÚsqlÖеÄÓ÷¨
sql ÖÐ order by ×Ó¾äÓÃÓÚ¶ÔЧ¹û¼¯ÅÅÐò£¬Ó﷨Ϊ£ºorder by column_name [asc | desc]¡£ËüÔÊÐíƾָ֤¶¨µÄÁлò±í´ïʽ¶Ô¼Í¼¾ÙÐÐÉýÐò»ò½µÐòÅÅÁУ¬¿Éͬʱ½ÓÊܶà¸öÁÐʵÏֶ༶ÅÅÐò¡£¿ÕÖµÅÅÐòÐÐΪ¿Éͨ¹ý is null ºÍ coalesce º¯ÊýÖ¸¶¨¡£
ÔÚ SQL ÖÐʹÓà ORDER BY
ÔÚ SQL ÖУ¬ORDER BY ×Ó¾äÓÃÓÚ¶ÔÅÌÎÊЧ¹û¼¯ÖеÄÐоÙÐÐÅÅÐò¡£ËüÔÊÐíÎÒÃÇƾָ֤¶¨µÄÁлò±í´ïʽ¶Ô¼Í¼¾ÙÐÐÉýÐò»ò½µÐòÅÅÁС£
Ó÷¨£º
SELECT column_list FROM table_name ORDER BY column_name [ASC | DESC];
µÇ¼ºó¸´ÖÆ
²ÎÊý£º
column_list£ºÒªÑ¡ÔñµÄÁС£
table_name£ºÒªÅÌÎÊµÄ±í¡£
column_name£ºÒªÅÅÐòµÄÁС£
ASC£ºÉýÐòÅÅÁУ¨Ä¬ÈÏ£©¡£
DESC£º½µÐòÅÅÁС£
ʾÀý£º
ΪÁË¶Ô employees ±íÖеÄÔ±¹¤°´ last_name ÉýÐòÅÅÐò£¬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏÂÅÌÎÊ£º
SELECT * FROM employees ORDER BY last_name ASC;
µÇ¼ºó¸´ÖÆ
Õ⽫±¬·¢ÒÔÏÂЧ¹û£º
| employee_id | first_name | last_name | |-------------|------------|------------| | 1 | John | Adams | | 2 | Jane | Doe | | 3 | Michael | Smith |
µÇ¼ºó¸´ÖÆ
ÅÅÐò¶à¸öÁУº
ORDER BY ×Ó¾ä¿ÉÒÔͬʱ½ÓÊܶà¸öÁУ¬´Ó¶øʵÏֶ༶ÅÅÐò¡£ÁеÄÅÅÐò˳Ðò½«¾öÒé×îÖÕЧ¹ûµÄÅÅÐò·½·¨¡£
SELECT * FROM employees ORDER BY last_name ASC, first_name DESC;
µÇ¼ºó¸´ÖÆ
´ËÅÌÎʽ«Ê×ÏÈ°´ last_name ÉýÐòÅÅÐò£¬È»ºó°´ first_name ½µÐòÅÅÐò¡£
ÅÅÐò¿ÕÖµ£º
ʹÓà ORDER BY ʱ£¬¿ÕÖµ½«±»ÊÓΪ×îС»ò×î´óÖµ£¬Ïêϸȡ¾öÓÚÅÅÐò˳Ðò¡£¿ÉÒÔͨ¹ýʹÓà IS NULL ºÍ COALESCE º¯ÊýÖ¸¶¨¿ÕÖµµÄÅÅÐòÐÐΪ¡£
×¢ÖØÊÂÏ
ORDER BY ×Ó¾ä±ØÐè·ºÆðÔÚ SELECT Óï¾äµÄĩβ¡£
Ë÷Òý¿ÉÒÔ´ó´óÌá¸ßʹÓà ORDER BY ʱÅÌÎʵÄÐÔÄÜ¡£
ÔÚʹÓà ORDER BY ¾ÙÐÐÅÅÐò֮ǰ£¬Ó¦Ë¼Á¿ÅÌÎÊЧ¹ûµÄÔ¤ÆÚÓÃ;¡£
ÒÔÉϾÍÊÇorder byÔÚsqlÖеÄÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡