MySQL中ORDER BY和GROUP BY是两个重要的SQL语句,它们的用法和区别在于:
ORDER BY可以按照指定的列进行排序,它可以按照升序或降序来排序,其语法为:
SELECT * FROM table_name ORDER BY column_name [ASC | DESC];
其中ASC表示升序,DESC表示降序,如果不指定,默认为升序。
GROUP BY可以按照指定的列进行分组,它可以将相同的值的记录分为一组,其语法为:
SELECT * FROM table_name GROUP BY column_name;
假设有一个表tbl_name,其结构如下:
+---------+---------+---------+ | name | age | score | +---------+---------+---------+ | jack | 20 | 90 | | mike | 20 | 80 | | lucy | 21 | 85 | | lily | 21 | 95 | +---------+---------+---------+
按照age升序,score降序排序:
SELECT * FROM tbl_name ORDER BY age ASC, score DESC;
结果如下:
+---------+---------+---------+ | name | age | score | +---------+---------+---------+ | jack | 20 | 90 | | mike | 20 | 80 | | lucy | 21 | 95 | | lily | 21 | 85 | +---------+---------+---------+
按照age分组:
SELECT * FROM tbl_name GROUP BY age;
结果如下:
+---------+---------+---------+ | name | age | score | +---------+---------+---------+ | jack | 20 | 90 | | lucy | 21 | 85 | +---------+---------+---------+
从上面的示例中可以看出,ORDER BY和GROUP BY在MySQL中的用法和区别。ORDER BY是按照指定的列进行排序,可以按照升序或降序来排序;GROUP BY是按照指定的列进行分组,只能按照升序来分组。
本文链接:http://task.lmcjl.com/news/10819.html