2012-01-16 41 views

回答

1

你可以使用一個表和觸發器來實現諸如序列的預言:

drop table if exists users_seq; 
create table users_seq 
(
next_val int unsigned not null default 0 
) 
engine=innodb; 

drop table if exists users; 
create table users 
(
user_id int unsigned not null, 
username varchar(32) unique not null 
) 
engine=innodb; 

delimiter # 

create trigger users_before_ins_trig before insert on users 
for each row 
begin 
declare v_id int unsigned default 0; 

select next_val + 1 into v_id from users_seq; 

set new.user_id = v_id; 

update users_seq set next_val = v_id; 

end# 

delimiter ; 

insert into users_seq values (0); 
insert into users (username) values ('alpha'),('beta'); 

Query OK, 2 rows affected, 1 warning (0.03 sec) 

select * from users_seq; 

+----------+ 
| next_val | 
+----------+ 
|  2 | 
+----------+ 
1 row in set (0.00 sec) 

select * from users; 

+---------+----------+ 
| user_id | username | 
+---------+----------+ 
|  1 | alpha | 
|  2 | beta  | 
+---------+----------+ 
2 rows in set (0.00 sec) 

insert into users (username) values ('alpha'); 

ERROR 1062 (23000): Duplicate entry 'alpha' for key 'username' 

select * from users_seq; 
+----------+ 
| next_val | 
+----------+ 
|  2 | 
+----------+ 
1 row in set (0.00 sec) 

select * from users; 

+---------+----------+ 
| user_id | username | 
+---------+----------+ 
|  1 | alpha | 
|  2 | beta  | 
+---------+----------+ 
2 rows in set (0.00 sec) 

insert into users (username) values ('gamma'); 

Query OK, 1 row affected, 1 warning (0.03 sec) 

select * from users_seq; 

+----------+ 
| next_val | 
+----------+ 
|  3 | 
+----------+ 
1 row in set (0.00 sec) 

select * from users; 

+---------+----------+ 
| user_id | username | 
+---------+----------+ 
|  1 | alpha | 
|  2 | beta  | 
|  3 | gamma | 
+---------+----------+ 
3 rows in set (0.00 sec) 

希望它能幫助:)

1

答案包含在你的問題中:根本不要讓它自動增加列。相反,你自己找出正確的值並處理重複的關鍵錯誤。

0

只需將字段設置爲PRIMARY而不帶AUTO_INCREMENT,那麼您可以控制它的值。

0

跨越這個「錯誤」剛剛來到。不要喜歡這種行爲,因爲它會使我的應用程序中的任何UNIQUE列的使用失效。

所以我的解決方案是:檢查是否存在唯一密鑰(與選擇)之前添加它,並從唯一鍵退出。