My studying notes for Java,Ruby,Ajax and other any interesting things.

星期三, 十月 21, 2009

mysql中的order by 不常用语法

先建一个表,填充些数据:
mysql> create table test(name varchar(10) not null, type varchar(10) not null);
mysql> insert into test(name,type) values
('Apples','Fruit'),
('Bananas','Fruit'),
('Carrots','Veg'),
('Onions','Veg'),
('Beer','Liquid'),
('Water','Liquid'),
('Crackers','Food');
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0
 
1:一种不是很常用的语法 :order by  1,2
这种语法中1 表示的是所选择的第一列,同理 2 表示select 的第二列。
mysql> select name from test order by 1;
+----------+
| name     |
+----------+
| Apples   |
| Bananas  |
| Beer     |
| Carrots  |
| Crackers |
| Onions   |
| Water    |
+----------+
mysql> select name from test order by 2;
ERROR 1054 (42S22): Unknown column '2' in 'order clause'
这里只选择了一列"name",但是却按第2列排序, 显然会出错。
 
mysql> select name ,type from test order by 2;
+----------+--------+
| name     | type   |
+----------+--------+
| Crackers | Food   |
| Apples   | Fruit  |
| Bananas  | Fruit  |
| Beer     | Liquid |
| Water    | Liquid |
| Carrots  | Veg    |
| Onions   | Veg    |
+----------+--------+
7 rows in set (0.00 sec)
 

2:mysql 对类char型或enum型的列进行排序的:
mysql> select name , type  from test 
 order by type='Veg' DESC,
               type='Fruit' DESC,
               type='Food' DESC,
               type='Liquid' DESC;
+----------+--------+
| name     | type   |
+----------+--------+
| Carrots  | Veg    |
| Onions   | Veg    |
| Apples   | Fruit  |
| Bananas  | Fruit  |
| Crackers | Food   |
| Beer     | Liquid |
| Water    | Liquid |
+----------+--------+
7 rows in set (0.00 sec)
上面type的类型如果为 enum 的话也一样ok.
 
这里也有一种更简单的方式
用字符串中 Field()函数来排序。
mysql> SELECT name
    -> FROM test
    -> ORDER BY FIELD(type,'Veg','Fruit','Food','Liquid');
FIELD :  返回值为str1, str2, str3,……列表中的str 的index。在找不到str 的情况下,返回值为 0 。
 
mysql> SELECT FIELD('ej', 'Hej', 'ej', 'Heja', 'hej', 'foo');
 
        -> 2
 
mysql> SELECT FIELD('fo', 'Hej', 'ej', 'Heja', 'hej', 'foo');
 
        -> 0