检查整数列值

时间:2014-02-26 12:58:33

标签: mysql


我在MySQL表中有一个整数列,现在表空。我想检查整数列值如下,但不返回任何内容。

SELECT IF(PROMO_NO = '', DATE_FORMAT(CURDATE(), '%y%u'), PROMO_NO) AS PROMO 
FROM PROMO_TYPE_P

// or
SELECT IF(PROMO_NO = 0, DATE_FORMAT(CURDATE(), '%y%u'), PROMO_NO) AS PROMO 
FROM PROMO_TYPE_P

// pehh, I tried this as well which is count value 0 but no success
SELECT IF((SELECT COUNT(*) FROM PROMO_TYPE_P) = 0, DATE_FORMAT(CURDATE(), '%y%u'), PROMO_NO)
AS PROMO FROM PROMO_TYPE_P

我不明白这个问题。有人有任何想法吗?

CREATE TABLE `PROMO_TYPE_P` (
  `PROMO_ID` int(6) UNSIGNED NOT NULL AUTO_INCREMENT,
  `PROMO_TYPE_CODE` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `PROMO_NO` int(6) UNSIGNED NOT NULL,
  `PROMO_DESC` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `PROMO_TRIGGER` tinyint(1) NOT NULL,
  `PROMO_TYPE` int(1) UNSIGNED NOT NULL,
  `PROMO_DISCOUNT` int(8) UNSIGNED NOT NULL,
  `PROMO_WORK` int(2) UNSIGNED NOT NULL,
  `PROMO_START_DATE` date NOT NULL DEFAULT '0000-00-00',
  `PROMO_END_DATE` date NOT NULL DEFAULT '0000-00-00',
  `PROMO_START_TIME` time NOT NULL DEFAULT '00:00:00',
  `PROMO_END_TIME` time NOT NULL DEFAULT '00:00:00',
  `PROMO_WORK_DAYS` int(7) UNSIGNED NOT NULL,
  `PROMO_BUNDLE` int(1) UNSIGNED NOT NULL,
  PRIMARY KEY (`PROMO_ID`),
  UNIQUE KEY `IDX_PROMO_NO` (`PROMO_NO`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

PS:我尝试的查询必须有效但没有任何反应。正如您在列中可以看到unique索引所示,因此我不确定与此相关的问题。我正在使用Toad for MySQL免费版。

enter image description here

解决方案:

SELECT IF(COUNT(*) = 0, DATE_FORMAT(CURDATE(), '%y%u'), 'DENEME') AS PROMO FROM PROMO_TYPE_P

2 个答案:

答案 0 :(得分:1)

当您的列为整数时,您正在检查空字符串。

试试这个

SELECT IF(PROMO_NO IS NULL, DATE_FORMAT(CURDATE(), '%y%u'), PROMO_NO) AS PROMO 
 FROM PROMO_TYPE_P

编辑:

SELECT IF(PROMO_NO = '' or PROMO_NO IS NULL or PROMO_NO =0, DATE_FORMAT(CURDATE(), '%y%u'), PROMO_NO) AS PROMO 
FROM PROMO_TYPE_P

EDIT2。

 SELECT IF(PROMO_NO IS NULL, 'THERE IS NULL VALUE', 'there is no null value') AS PROMO 
 FROM PROMO_TYPE_P

答案 1 :(得分:1)

PROMO_NO被定义为非空无符号整数:

PROMO_NO int(6) UNSIGNED NOT NULL,

此外,它被声明为unique,因此任何值最多只能出现在一行上。

有问题的查询是:

SELECT IF(PROMO_NO = '', DATE_FORMAT(CURDATE(), '%y%u'), PROMO_NO) AS PROMO 
FROM PROMO_TYPE_P;

没有过滤。因此,如果它没有返回任何行,那么它将查询一个空表。您确定已连接到正确的数据库吗?尝试运行:

SELECT *
FROM PROMO_TYPE_P;

我应该补充说if语句混合了字符串和整数。我不认为这会导致没有返回任何行,除非发生错误(并且您没有提到这样的错误)。

编辑:

如果您希望在表格为空时返回当前日期,否则返回促销,然后使用union all

select max(DATE_FORMAT(CURDATE(), '%y%u'))
from dual
where not exists (select 1 from promo_type_p)
union all
select promo_no
from promot_type_p;