Currently in my ecommerce website have 2 tables below:
I used 2 query to generate
$query = $this->db->query("SELECT count(*) AS hits, product_id
FROM visitors
GROUP BY product_id");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row){
$hits = $row->hits;
$product_id = $row->product_id;
$data = array(
'product_id' => $product_id ,
'hits' => $hits
);
$this->db->insert('visitor_days', $data);
}
}
Problem:
If 10k record, the updating very slow. How to improve this query?
Can I make it in single query?
visitors
- ID product_id date
- 534024 69082 2012-09-25
- 534025 69082 2012-09-25
- 534026 69082 2012-09-25
- 534027 69082 2012-09-25
- 534028 53042 2012-09-25
- 534029 53042 2012-09-25
visitor_days
- ID product_id hits
- 534024 69082 4
- 534025 53042 2
You should be able to do it in one INSERT INTO statement by using the SELECT clause
This should be immensely faster in your 10k case because you will be doing one query instead of 10,001.