Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve MySQL query

Tags:

sql

php

group-by

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
like image 739
Vill Raj Avatar asked Jul 11 '26 19:07

Vill Raj


1 Answers

You should be able to do it in one INSERT INTO statement by using the SELECT clause

INSERT INTO visitor_days
  (product_id, hits)
  SELECT product_id, COUNT(*)
    FROM visitors
    GROUP BY product_id

This should be immensely faster in your 10k case because you will be doing one query instead of 10,001.

like image 182
walrii Avatar answered Jul 13 '26 07:07

walrii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!