在我的网页中,有一个CSV导入部分。用户可以导入数千条记录。我需要将 csv 详细信息插入 2 个表中。
第一个表包含基本信息。第二个包含其他附加信息。所以我需要将第一个表的插入 ID 保存到第二个表中。
对于上述要求,我编写了 2 mysql 语句。但是导入需要更多时间。在这里,是否可以使用单个查询将记录插入 2 个表中?
请指教。
您不能一次插入两个表(因为您需要第一个表中的 id),但您可以为第一个表逐个插入,为第二个表插入一个查询
,如下所示:$main_data = array('data1', 'data2', 'data3');
$new_data = array();
foreach($main_data as $data) {
mysql_query("insert into table1 (data) values ('$data')");
$new_id = mysql_insert_id();
// Save the new id into an array + the data
$new_data[$new_id] = $main;
}
$insert_into = array();
// Create a new insert statement
foreach($new_data as $new_key => $data) {
$insert_into[] . "($new_key, '$data')"
}
$imploded_data = implode(',', $insert_into);
if (count($insert_into) > 0) {
// The result will be something like Insert into `table2` (id, value) values (1, 'data1'), (2, 'data2'),(3, 'data3');
mysql_query("insert into `table2` (id, value) values $imploded_data");
}
试试这种方式..
$main_data = array('dino', 'babu', 'john');
foreach($main_data as $main) {
// Insert main to 1st table
mysql_query("MY INSERT QUERY TO TABLE 1");
// Get the last insert id
$new_id = mysql_insert_id();
// Insert the sub data to 2nd table using the insert id
mysql_query("MY INSERT QUERY TO TABLE 2 USING $new_id ");
}
不可以,一次只能插入 1 个表。
使用事务(http://dev.mysql.com/doc/refman/5.0/en/commit.html)来维护数据的原子性。
由于您尚未共享您的架构,我将以同样的方式告诉您故事:)
我会走这条路
步骤 1.old_max_import_id = select max(id) from csv_imports;
步骤 2.将数据导入csv_imports
表
步骤 3.通过运行以下单个查询将相同的数据复制到csv_imports2
insert into csv_imports2(fielda,fieldb,fieldc......)
select fielda,fieldb,fieldc .....from csv_imports
where id > old_max_import_id;
我认为你可以在 yii 中轻松实现这一点。我假设您正在将csv数据导入表中以进行Insertion
.如果您通过 csv 导入进行更新,策略将发生重大变化。在这种情况下csv_imports
表上的插入/更新触发器将为您提供帮助。
这需要更多时间,因为您为每行 CSV 运行查询。尝试一次连接所有 SQL 语句和执行
。insert into table_one (First, Last) values ('Fred','Smith'),
('John','Smith'),
('Michael','Smith'),
('Robert','Smith');
insert into table_two (First, Last) values ('Fred','Smith'),
('John','Smith'),
('Michael','Smith'),
('Robert','Smith');