2017-06-19 325 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

而且,如果我使用您编写的代码,则每次执行此代码时,它都会复制以前的数据 –

相关问题