Search code examples
mysqlquery-optimization

optimize way of following mysql query


$sql = "SELECT c.id as c_id, w.id as w_id, c.city as cms_city,
               s.id as state_id, s.state_code as state
         FROM `cms_hotel` as c
         join webgeocities as w on c.city=w.name
                  and c.country_code=w.country_code
         join states as s on (w.state_code= s.state_code)
         group by c.id";
$result = mysqli_query($conn,$sql) or die( mysqli_error());
while($row = mysqli_fetch_array($result)){

    $upd = "update cms_hotel set city_id  = '".$row['w_id'].
                  "' where id = '".$row['c_id']."'";
    $upd_result = mysqli_query($conn,$upd) or die( mysqli_error());

    $sel = "select id from city_matching where city='".$row['cms_city'].
                    "' and state_id='".$row['state_id']."'";
    $sel_result = mysqli_query($conn,$sel) or die( mysqli_error());
    if (mysqli_num_rows($sel_result) == 0) {
        $ins = "insert into city_matching 
                 set city_name  = '".$row['cms_city'].
                  "' , state_id = '".$row['state_id']."'";
        $ins_result = mysqli_query($conn, $ins) or die( mysqli_error());
    }
}

Solution

  • Remove loop and SELECT expressions from code. Run next queries:

    Update:

    UPDATE `cms_hotel` as c 
    JOIN webgeocities as w ON c.city = w.name 
      AND c.country_code = w.country_code
    JOIN states AS s ON w.state_code = s.state_code
    SET c.city_id = w.id, 
    GROUP BY c.id
    

    Insert:

    INSERT INTO city_matching (city_name, state_id)
    SELECT c.city, s.id
    FROM `cms_hotel` as c 
    JOIN webgeocities as w ON c.city = w.name 
      AND c.country_code = w.country_code
    JOIN states AS s ON w.state_code = s.state_code
    LEFT JOIN city_matching AS cm ON cm.city=c.city
      AND cm.state_id=s.id
    WHERE cm.city IS NULL
    GROUP BY c.city, s.id