【发布时间】:2015-02-04 23:56:22
【问题描述】:
我有一张这样的桌子:
create table thing (
id bigint primary key auto_increment,
code integer not null,
description varchar(100)
);
表格通常有连续的代码,但用户可以将生成的代码更改为其他更方便他的代码,这样他就可以打破链。他也可以删除一些thing。
所以,我试图弄清楚如何获得第一个未使用的代码。
例如:
- 如果我有 1、2,我想得到 3
- 如果我有 1、2、3、50 和 51,我想得到 4。
我认为在接下来的两个查询中可以解决我的问题,但它们似乎都不是一个好的选择。
第一个使用exists,我认为它是低效的,因为它具有二次顺序。
select min(code)+1 from thing t
where not exists (select * from thing where code = t.code + 1);
第二个是不可能在 Hibernate HQL 查询上实现的,因为我正在尝试使用一个奇怪的连接子句t1.code = t2.code - 1
select min(t1.code)+ 1
from thing t1 left join thing t2 on t1.code = t2.code - 1
where t2.id is null;
【问题讨论】:
-
这是一个很好的相关问题,但它并没有解决我的问题。解决方案包括我不能在 Hibernate 上使用的 Exists 或奇怪的左连接
-
获得第一个“未使用”代码后,您将如何处理?
-
我想建议用户使用该值,因此他不必考虑
thing的新代码。