我的桌子看起来像这样
mysql> select * from rc;
+----+----------------------------+----------------------------+----------------------------+
| id | business_date | cutoff_dt | recon_dt |
+----+----------------------------+----------------------------+----------------------------+
| 1 | 2017-03-21 16:50:29.032000 | 2017-03-21 16:50:31.441000 | 2017-03-21 16:50:32.832000 |
+----+----------------------------+----------------------------+----------------------------+
1 row in set (0.00 sec)
我想运行查询
-select * from rc
business_date = '2017-03-17'
- if
cutoff_dt`为null或为空,它将显示null,否则显示为null
我把它写进了shell脚本。
#! /bin/bash
mysql -u root -p <<rcard
use rcard;
SELECT *
(CASE WHEN (cut_off_dt = "NULL")
THEN
echo "Null"
ELSE
echo "NOT NULL"
END)
from rc WHERE business_date = '2017-03-17';
rcard
但我收到错误
ERROR 1064 (42000) at line 2: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(CASE WHEN (cut_off_dt = "NULL")
THEN
echo "Null"
ELSE
' at line 2
在MySQL中编写IF ELSE是正确的方法吗?
答案 0 :(得分:2)
这不是检查NULL
值的正确方法。
试试这个:
SELECT *,
IF(mepslog_cut_off_dt IS NULL, 'NULL', 'NOT NULL')
from rc_mepslog
WHERE mepslog_business_date = '2017-03-17';
您也可以使用CASE
表达式:
SELECT *,
CASE
WHEN mepslog_cut_off_dt IS NULL THEN 'NULL'
ELSE 'NOT NULL'
END
from rc_mepslog
WHERE mepslog_business_date = '2017-03-17';
答案 1 :(得分:1)
SELECT *, (CASE WHEN (mepslog_cut_off_dt IS NULL)
THEN
'Null'
ELSE
'NOT NULL' END) from rc WHERE business_date = '2017-03-17'
要比较值是否为null,请使用column IS NULL
代替column = 'NULL'
;后者会检查你要比较的列是否有字符串'null'
答案 2 :(得分:1)
在select *
之后缺少逗号,并且您在查询中指定的任何表名都不存在。要将表与列分开,请使用点.
。还有其他错误的书面列名。此外,您不使用echo
,只需指定要执行的操作。另外,我建议在案例(AS 'nullOrNotNull'
)
SELECT * ,
CASE WHEN cut_off_dt IS NULL
THEN
'Null'
ELSE
'NOT NULL'
END AS 'nullOrNotNull'
from rc WHERE business_date = '2017-03-17';