如果值为NULL,则将值递增1

时间:2013-07-28 20:50:00

标签: mysql

如果表格中至少有一行,则下面的查询有效。我希望它在返回NULL的情况下返回1。

mysql> desc users_map_item;
+----------------+-----------------------+------+-----+---------+-------+
| Field          | Type                  | Null | Key | Default | Extra |
+----------------+-----------------------+------+-----+---------+-------+
| map_user_id    | mediumint(8) unsigned | NO   | MUL | NULL    |       |
| map_item_id    | mediumint(8) unsigned | NO   | PRI | NULL    |       |
| unique_item_id | mediumint(8) unsigned | NO   |     | NULL    |       |
| item_owner     | mediumint(8) unsigned | NO   |     | NULL    |       |
| privilege      | tinyint(1)            | YES  |     | NULL    |       |
+----------------+-----------------------+------+-----+---------+-------+

SELECT case when unique_item_id IS NULL then isnull(max(unique_item_id)+1) else     
max(unique_item_id)+1 end as unique_item_id FROM users_map_item WHERE map_user_id = 1;

3 个答案:

答案 0 :(得分:2)

SELECT MAX(COALESCE(unique_item_id, 0)) + 1 FROM users_map_item WHERE ...

应该这样做。

答案 1 :(得分:2)

而不是isnull(max(unique_item_id)+1)只需输入1

答案 2 :(得分:1)

如果值为NULL,则添加1只会创建NULL值。

此外,case语句应该使用条件的max()聚合函数。

SELECT (case when max(unique_item_id) IS NULL then 1
             else max(unique_item_id)+1
        end) as unique_item_id
FROM users_map_item
WHERE map_user_id = 1;

这可以简化为:

select coalesce(max(unique_item_id)+1, 1)
FROM users_map_item
WHERE map_user_id = 1;

编辑: 以下是关于这个特殊情况下隐藏列(MySQL扩展)的可能性。当没有行时,您的原始查询有点令人费解。以下查询将返回值为NULL的一行:

select max(unique_item_id)
from users_map_item
where map_user = 1;

但是,此查询返回 no 行,这与具有NULL值的行不同:

select unique_item_id
from users_map_item
where map_user = 1;

这个表达式混合了两个:

SELECT (case when unique_item_id IS NULL then 1
             else max(unique_item_id)+1
        end) as unique_item_id
FROM users_map_item
WHERE map_user_id = 1;

是返回一行还是零行?答案是“1”,因为它是一个聚合查询。但unique_item_id对该行的价值是多少?嗯,没有这样的价值。我认为“none”与NULL不同,但MySQL将其视为NULL,这就是查询有效的原因。这在大多数其他数据库中都不起作用。