あなたがInnoDBエンジンを使用している場合、あなたはこのようにトリガーを使用することができます。
CREATE TRIGGER `your_table_before_ins_trig` BEFORE INSERT ON `your_table`
FOR EACH ROW
begin
declare next_id int unsigned default 1;
-- get the next ID for your Account Number
select max(ID) + 1 into next_id from your_table where Account = new.Account;
-- if there is no Account number yet, set the ID to 1 by default
IF next_id IS NULL THEN SET next_id = 1; END IF;
set new.ID= next_id;
end#
注意!上記のSQL文で区切り文字列は#です!あなたはこのような任意のAUTO_INCREMENT機能せず、それを作成した場合
このソリューションは、あなたのようなテーブルのために働く:
CREATE TABLE IF NOT EXISTS `your_table` (
`ID` int(11) NOT NULL,
`Account` int(11) NOT NULL,
PRIMARY KEY (`ID`,`Account`)
);
今、あなたはこのように自分の価値観を挿入することができます。
INSERT INTO your_table (`Account`) VALUES (1);
INSERT INTO your_table (`Account`, `ID`) VALUES (1, 5);
INSERT INTO your_table (`Account`) VALUES (2);
INSERT INTO your_table (`Account`, `ID`) VALUES (3, 10205);
それはになりますこれは:
ID | Account
------------------
1 | 1
2 | 1
1 | 2
1 | 3
出典
2014-05-05 13:09:09
Pat
あなたはどのエンジンを使用していますか? – Mark