1

我想优化我对 codeigniter 的查询。

此查询有效,但似乎将结果插入我的数据库表需要时间。

$this->db->select('client_id');
$this->db->from('event');       
$query = $this->db->get();  

foreach($query->result_array() as $row){
  $client_id = $row['client_id'];
  $data = array( 'event_id' => $event_id , 'client_id' => $client_id);          
  $this->db->insert('event_entry', $data);                  
}

我想知道是否有办法对其进行优化。

4

3 回答 3

3

与其进行n多次插入,不如仅进行一次插入应该可以提高执行时间。您可以在 codeigniters 活动记录中使用insert_batch().

$this->db->select('client_id');
$this->db->from('event');       
$query = $this->db->get();  

$data = array();

foreach($query->result_array() as $row){
  $client_id = $row['client_id'];
  array_push($data, array('event_id' => $event_id , 'client_id' => $client_id));          
}

$this->db->insert_batch('event_entry', $data); 

产生:

INSERT INTO event_entry (event_id, client_id) VALUES ('event_id', 'client_id'), ('event_id', 'client_id'), ...
于 2013-09-10T08:53:22.190 回答
2

Replace all of that code with:

$this->db->query("
INSERT INTO event_entry (event_id, client_id)
SELECT ?, client_id
FROM event
", array($event_id));

And you will clearly notice the difference in execution time :) Plus in my opinion, having less code to worry about.

This query can't be run from Active Records, but it should be quite self explaining. Just like a normal SELECT, if fetches client_id and the already defined value $event_id by each event row. It then takes these values, and INSERT them into event_entry.

Note that ? and array($event_id) insert the value into the query escaped (and safe). Never insert into query as SELECT {$event_id}, client_id unless you know what you're doing.

Jeemusu's solution is indeed a nice way to do it through Active Records, but if it's performance you want all the way, one query is faster than two in this case.

于 2013-09-10T08:50:17.510 回答
0

您可以使用 insert_batch 命令将数据插入数据库。使用 foreach 循环生成数据数组,然后使用 insert_batch 数据库。http://ellislab.com/codeigniter/user-guide/database/active_record.html

如果您需要任何帮助,请告诉我

于 2013-09-10T08:57:38.677 回答