2016-01-14 51 views
0

新的唯一ID我有一個表創建的Postgres

id | entry | field | value 
1 | 1  | name | Egon 
2 | 1  | sname | Smith 
3 | 1  | city | Los Angeles 
4 | 2  | name | Stephe 
5 | 2  | sname | Mueller 
6 | 2  | city | New York 

其中id是PK和自動遞增。具有相同entry的行屬於一起,它們是一種數據集。我想爲新的entry添加新行(應該有值3)。

我的問題是:如何獲得entry的下一個值,它是唯一的? 在使用類似

SELECT MAX(entry)+1 

但是當兩個查詢在同一時間做,我會得到entry = "3"對他們倆的那一刻IM。我使用PHP編碼。

+1

糾正你的數據庫設計。 entryid應該是主鍵 –

+1

你有一個建模問題而不是序列問題。 –

+0

id似乎是(代理)主鍵,{entry,field}看起來像候選鍵。可能需要將te表分成兩個或三個表,這將產生一個EAV模型(這通常被許多人認爲是反模式) – joop

回答

0

使用,你已經得到了作爲插入一個唯一的標識符序列(不要把這一任務交給PHP):

INSERT INTO "my_table" ("entry", "field", "value") VALUES (currval(('"my_current_id_sequence"'::text)::regclass), 'any_field_info', 'any_value_info'); 

這樣Postgres將使用正確數量的每次。

另一個問題是創建一個序列並在INSERT上使用它,只需使用nextval(('"my_new_sequence"'::text)::regclass)作爲entry的值,您甚至可以將其用作默認值。

如果您需要知道哪些值被用來只需添加RETURNING entryINSERT

CREATE SEQUENCE alt_serial START 101; 
ALTER TABLE "my_table" 
ALTER COLUMN "entry" SET DEFAULT nextval(('"alt_serial"'::text)::regclass); 

INSERT INTO "my_table" ("entry", "field", "value") VALUES (DEFAULT, 'any_field_info', 'any_value_info') RETURNING entry; 
0

你可以做一些循環來增加每個循環的入口。如果你想用相同的條目添加更多的行,在1循環中傳遞更多的參數。

class foo{ 
protected $foo = []; 
public function set_foo($arguments = []){ 
$this->foo = $arguments; 
} 

public function insert_rows(){ 

$entry = // last entry from the db (number)- your logic here 
$num_of_foos = count($this->foo); 

$i = 0; 

$query = 'INSERT INTO table(entry, field, value) VALUES'; 
while($i<$num_of_foos){ 
    if($i>1){$query .= ',';} // adds the comma if loop repeats more than once 
    $query .= '("'; 
    $query .= $entry; // entry number for the first item 
    $query .= ',' . $this->foo[$i] . ',' . $some_Value; 
    $query .= '")'; 
    $i++; 
} // end of while loop 
$entry++; 
} // end of function insert_rows() 
} // end of class foo 

//now all you need to do is set the foo 

$foo = new foo; 
$foo->set_foo('lalala'); // sets one argument with new entry 
$foo->set_foo('jajaja'); // sets another argument with new entry 
$foo->set_foo('lala', 'jaja'); // sets two arguments with the same entry 
0

您需要:

  • 創建序列

    CREATE SEQUENCE table_entry_seq; 
    
  • 然後,當你需要添加一個新的entry時,獲取該序列的下一個值:

    SELECT nextval(('"table_entry_seq"'::text)::regclass)