用法:select coalesce(a,b,c) a,b,c之間可多個
如果a==null,則選擇b;如果b==null,則選擇c;如果a!=null,則選擇a;如果a b c 都為null ,則返回為null(沒意義)。
MySQL> select name from test1;+--------+| name |+--------+| 小明 || 小王 || 小麗 || 小王 || 小明 || 小明 || NULL |+--------+7 rows in set (0.00 sec)mysql> select coalesce(name,'1') from test1;+--------------------+| coalesce(name,'1') |+--------------------+| 小明 || 小王 || 小麗 || 小王 || 小明 || 小明 || 1 |+--------------------+7 rows in set (0.00 sec)mysql> select coalesce(name,null,'11') from test1;+--------------------------+| coalesce(name,null,'11') |+--------------------------+| 小明 || 小王 || 小麗 || 小王 || 小明 || 小明 || 11 |+--------------------------+7 rows in set (0.00 sec)mysql> select coalesce(name,null,null,'111') from test1;+--------------------------------+| coalesce(name,null,null,'111') |+--------------------------------+| 小明 || 小王 || 小麗 || 小王 || 小明 || 小明 || 111 |+--------------------------------+7 rows in set (0.00 sec)
mysql> select name,sum(singin) from test1 group by name;+--------+-------------+| name | sum(singin) |+--------+-------------+| 小麗 | 2 || 小明 | 7 || 小王 | 7 |+--------+-------------+3 rows in set (0.00 sec)mysql> select coalesce(name,'總數'),sum(singin) from test1 group by name with rollup;+-------------------------+-------------+| coalesce(name,'總數') | sum(singin) |+-------------------------+-------------+| 小麗 | 2 || 小明 | 7 || 小王 | 7 || 總數 | 16 |+-------------------------+-------------+4 rows in set (0.01 sec)
當字段的值是null時,只能通過is null 或 is not null來查詢,不能用=null 或!=null來查詢。
若字段a的值是null,字段b的值是null,那么,a=b是會返回false的。可使用<=>運算符,那么,a<=>b會返回true。
mysql> select distinct a.name from test1 a,test1_copy b where a.name = b.name;+--------+| name |+--------+| 小明 || 小王 |+--------+2 rows in set (0.00 sec)mysql> select distinct a.name from test1 a,test1_copy b where a.name <=> b.name;+--------+| name |+--------+| 小明 || 小王 || NULL |+--------+3 rows in set (0.00 sec)
新聞熱點
疑難解答