【Mysql 學習】流程函式

楊奇龍發表於2011-01-01

--流程函式if ,ifnull ,case 語句!
mysql> create table sal (id int,sal decimal (9,2));
Query OK, 0 rows affected (0.06 sec)
mysql> insert into sal values (1,1000),(2,2000),(3,3000),(4,4000),(5,null);
Query OK, 5 rows affected (0.01 sec)
Records: 5  Duplicates: 0  Warnings: 0
--if(EXP,T,F) EXP 為真則返回T,EXP為假,則返回F
mysql> select * from sal;
+------+---------+
| id   | sal     |
+------+---------+
|    1 | 1000.00 |
|    2 | 2000.00 |
|    3 | 3000.00 |
|    4 | 4000.00 |
|    5 |    NULL |
+------+---------+
5 rows in set (0.00 sec)

mysql> select id, if(sal > 3000,'high','low') from sal;
+------+-----------------------------+
| id   | if(sal > 3000,'high','low') |
+------+-----------------------------+
|    1 | low                         |
|    2 | low                         |
|    3 | low                         |
|    4 | high                        |
|    5 | low                         |--這裡null >3000 為假!
+------+-----------------------------+
5 rows in set (0.01 sec)
--IFNULL(VAL,N)如果val 為null 則返回N
mysql> select id, ifnull(sal,0) from sal;
+------+---------------+
| id   | ifnull(sal,0) |
+------+---------------+
|    1 |       1000.00 |
|    2 |       2000.00 |
|    3 |       3000.00 |
|    4 |       4000.00 |
|    5 |          0.00 |
+------+---------------+
5 rows in set (0.01 sec)
--case 語句和oracle的一樣了!
mysql> select case when sal<=3000 then 'low' else 'high' end from sal;
+------------------------------------------------+
| case when sal<=3000 then 'low' else 'high' end |
+------------------------------------------------+
| low                                            |
| low                                            |
| low                                            |
| high                                           |
| high                                           |
+------------------------------------------------+
5 rows in set (0.00 sec)
mysql> select id, case sal when 2000 then 'low' when 3000 then 'mid' else 'high' end from sal;
+------+--------------------------------------------------------------------+
| id   | case sal when 2000 then 'low' when 3000 then 'mid' else 'high' end |
+------+--------------------------------------------------------------------+
|    1 | high                                                               |
|    2 | low                                                                |
|    3 | mid                                                                |
|    4 | high                                                               |
|    5 | high                                                               |
+------+--------------------------------------------------------------------+
5 rows in set (0.01 sec)

這裡只是簡單介紹,跟多的需要在實踐中學習!拋磚引玉了,呵呵

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22664653/viewspace-683150/,如需轉載,請註明出處,否則將追究法律責任。

相關文章