2017-06-19 160 views
0

請幫助我,在第一個表中插入數據後,如何將數據從一個表插入另一個表?

在第一個表中插入數據後,如何將數據從一張表插入另一張表? 我寫了一個查詢,但它有問題,它說「未知列'test.ProjectNumber'」。我應該先定義它嗎? 我想從test2.PN 插入數據test.ProjectNumber請幫我

代碼:

/** 
* Insert a record on another table 
*/ 

// SQL statement parameters 
$insert_table = 'test2';  
$insert_fields = array( 
    'test2.PN' => 'test.ProjectNumber', 
); 

// Insert record 
$insert_sql = 'INSERT INTO ' . $insert_table 
    . ' (' . implode(', ', array_keys($insert_fields)) . ')' 
    . ' VALUES (' . implode(', ', array_values($insert_fields)) . ')'; 

sc_exec_sql($insert_sql); 

回答

0

你的SQL是計算如下:

INSERT INTO test2 (test2.PN) VALUES (test.ProjectNumber); 

這是無效的,因爲test.ProjectNumber在這方面不被理解。

我想你需要做的是兩個單獨的INSERT語句如下:

-- assumes that the number has not been inserted into test2 yet, 
-- just insert the same value into both tables: 
INSERT INTO test2 (test2.PN) 
VALUES (somevalue); 

INSERT INTO test (test.ProjectNumber) 
VALUES (somevalue); 

,或者如果第一行已經插入(目前尚不清楚表格的問題),您可以選擇價值插入,但你需要能夠識別行(我使用123

-- If test2 already contains the row you need to insert from 
-- then you need to select that row to insert the new row in test 
INSERT INTO test (test.ProjectNumber) 
SELECT test2.PN 
FROM test2 
WHERE test2.Id = someid; 

希望這有助於 - 我還沒有翻譯這個到PHP給你,這部分作爲練習你,但部分原因是我的php很生鏽......

+0

謝謝回答我的朋友。但是我想每次輸入第一個表時都要插入數據。如觸發器或存儲過程。你知道爲什麼test.ProjectNumber不理解嗎? –

+0

而且,如果我使用您編寫的代碼,則每次執行此代碼時,它都會複製以前的數據 –

相關問題