优化跟随mysql查询的方式

时间:2016-08-24 13:19:26

标签: mysql query-optimization

$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());
    }
}

1 个答案:

答案 0 :(得分:0)

从代码中删除循环和SELECT表达式。运行下一个查询:

更新

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 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