標籤:select 員工 函數 cot 替換 oal 預設值 pre ams
COALESCE函數從值列表中返回第一個非NULL的值,當遇到NULL值時將其替換為0。 coalesce(str1,str2....);
e.g. 需要在表中查出所有比‘WARD‘提成(COMM)低的員工,提成為NULL的員工也包括在內。 (個人意見,如果資料庫提成欄位預設值不是為0值的話肯定是開發那個的錯)。
select ename,comm from emp where coalesce(comm,0) < (select comm from emp whrer ename ="WARD");
結果:
+--------+------+| ename | comm |+--------+------+| SMITH | NULL || ALLEN | 300 || JONES | NULL || BLAKE | NULL || CLARK | NULL || SCOTT | NULL || KING | NULL || TURNER | 0 || JAMES | NULL || MILLER | NULL || ADAMS | NULL || FORD | NULL |+--------+------+12 rows in set
返回非NULL值:
select ename, comm,coalesce(comm,0) from emp where coalesce(comm,0) < (select comm from emp where ename = ‘WARD‘);
+--------+------+------------------+| ename | comm | coalesce(comm,0) |+--------+------+------------------+| SMITH | NULL | 0 || ALLEN | 300 | 300 || JONES | NULL | 0 || BLAKE | NULL | 0 || CLARK | NULL | 0 || SCOTT | NULL | 0 || KING | NULL | 0 || TURNER | 0 | 0 || JAMES | NULL | 0 || MILLER | NULL | 0 || ADAMS | NULL | 0 || FORD | NULL | 0 |+--------+------+------------------+12 rows in set
mysql coalesce函數