2012-03-08 40 views
2

我試圖找出如何做一個表3列:auto_increment列爲一組行嗎?

unique_id, type, version 

哪裏UNIQUE_ID爲AUTO_INCREMENT每個記錄,和版本是對每種類型AUTO_INCREMENT。

目的是,當我插入我只需要指定'類型'和unique_id和version_id自動生成。例如:

insert type 'a', then values are: 1 , a , 1 
insert type 'a', then values are: 2 , a , 2 
insert type 'a', then values are: 3 , a , 3 
insert type 'b', then values are: 4 , b , 1 
insert type 'b', then values are: 5 , b , 2 
insert type 'a', then values are: 6 , a , 4 

而且這將是公平地說,這樣的設置是不是真的歸?相反,它應該是兩張桌子?

+0

對於版本不是自動增量,因爲它不會在每個插入上增加。你正在談論觸發一個存儲過程的觸發器。它可以作爲子表完成,在這種情況下,版本不在此表中,而是在子表中。儘管如此,版本仍然沒有自動增量。 – Brian 2012-03-08 23:01:08

回答

1

您不能爲每種類型生成自動生成的序列,但您可以生成自己的序列。

insert into the_table (type, version) 
select 'a', 1 + IFNULL(max(version), 0) 
    from the_table 
    where type = 'a'; 
+0

輝煌!鑑於'a'是給定語言的變量。如果'where type ='a''可能不會返回任何東西,您應該返回'0'而不是'max(version)'。 +1 – 2012-03-09 00:28:35

+0

@碎片:好點!謝謝 :) – 2012-03-09 01:03:01

0

如果表格中會有很多行(並且取決於您要做什麼),那麼最好爲每個版本分別創建表格。然後,將每種類型插入到適當的版本表中。

相關問題