2011-04-13 45 views
1

如果我有這樣的如何在一個表中將兩個表與一個自動創建的id鏈接起來?

tbl_attributes 
--------------- 
id_attrib (auto incremented, primary key) 
col1 
col2 

一個表,另一個表

tbl_weight 
-------------- 
id_attrib *(not primary key)* 
field 

當談到時間,我插入值COL1和COL2的id_attrib是自動遞增將值插入表tbl_attributes 。我怎麼能插入id_attribute相同的自動遞增值到表tbl_weight中的字段id_attrib。這樣做的原因是因爲 我正在尋找輸入到tbl_attributes中的特定值,並且一旦im查找的值已被插入到tbl_attributes中,那麼與此相關的更多信息將被輸入到tbl_weight中。

否則,如果我結合這看起來像

tbl_attributes 
---------------- 
id_attrib 
col1 
col2 
field (from tbl_weight table) 

領域列將包含空數據了很多,當事情被滿足,我不想那樣做將只包含數據的表。

所以也許獲取當前auto_increment被用於tbl_attributes並插入該值。我正在考慮使用innodb格式,但我對這個世界很陌生,事情可能會搞砸。

回答

2
$sql = "INSERT INTO tbl_attributes VALUES(...)"; 
$res = mysql_query($sql); 

if ($res) { 
    $last_autoincrement_id = mysql_insert_id(); 
    // add code here 
    } 

手冊:mysql_insert_id()

檢索由先前的 一個 AUTO_INCREMENT列生成的ID查詢(通常是INSERT)。

現在您可以將該ID用於另一個INSERT查詢(tbl_weight)。

例子:

$sql = "INSERT INTO tbl_weight VALUES('$last_autoincrement_id', ...)"; 
mysql_query($sql); 

注意:不要忘記檢查mysql_query()結果。

+0

我從來沒有檢查查詢的結果,因爲我沒有看到一個目的。它的目的是什麼? thnx – 2011-04-13 02:41:52

+0

檢查結果的目的是什麼?要獲得請求是否成功?例如。 'mysql_query('BAD MYSQL REQUEST')'...這會引發錯誤。 – Wh1T3h4Ck5 2011-04-13 02:44:32

2

插入第一個自動增量表後,調用php函數mysql_insert_id()。這將返回前一個插入的自動遞增ID,您可以在後續插入中使用它。由PHP函數調用的本地MySQL的功能是LAST_INSERT_ID()

$result = mysql_query("INSERT INTO tbl_attributes (col1, col2) VALUES ('val1', 'val2');"); 

if ($result) 
{ 
    // Get the auto increment id from the first INSERT 
    $last_id = mysql_insert_id(); 
    // And use it in the second INSERT 
    $result2 = mysql_query("INSERT INTO tbl_weight (id_attrib, field) VALUES ($last_id, 'fieldval');"); 
} 
else // first insert failed 

Official PHP documentationmysql_insert_id()

相關問題