0

如果表中至少有一行,则以下查询有效。如果它返回,我希望它返回 1 NULL

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;
4

3 回答 3

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

应该做的伎俩。

于 2013-07-28T20:51:47.660 回答
2

而不是isnull(max(unique_item_id)+1)仅仅键入1.

于 2013-07-28T20:52:56.640 回答
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;

但是,此查询不返回任何行,这与具有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该行的值是多少?好吧,没有这样的价值。我认为“无”与 不同NULL,但 MySQL 将其视为NULL,这就是查询有效的原因。这在大多数其他数据库中不起作用。

于 2013-07-28T20:52:51.627 回答