将一个表中的2个字段组合成43,000条记录

时间:2014-03-23 05:33:08

标签: php mysql loops while-loop

我有一个代码,我希望将同一个表中的两个字段组合到同一个表中的另一个字段,并从另一个表中填写StateName

locations表有43,000条记录

我想改变这个

Table: states_cache            Table: locations
StateName | StateInitials      LocationID |  City       | StateInitials | StateName | Combo
------------------------       --------------------------------------------------------------
Missouri  |  MO                32500      | Springfield | MO            |           |
Kansas    |  KS                34151      | Topeka      | KS            |           |

到此

Table: states_cache            Table: locations
StateName | StateInitials      LocationID |  City       | StateInitials | StateName | Combo
------------------------       --------------------------------------------------------------
Missouri  |  MO                32500      | Springfield | MO            | Missouri  | Springfield MO
Kansas    |  KS                34151      | Topeka      | KS            | Kansas    | Topeka KS

这是我的代码......

我尝试运行它,它只是给我加载屏幕......

$conn = &$GLOBALS["dbSettings"]->GetConnection();

$sql = "SELECT City, StateInitials, LocationID, StateInitials FROM locations";
            $rs = $conn->Execute($sql);

        while (!$rs->EOF)
            { 
                $sql2 = "SELECT StateName FROM states_cache WHERE StateInitials ='" . $rs->fields[3] . "'";
                $rs2 = $conn->Execute($sql2);
                if ($rs2 === false) die('select error: ' . $conn->ErrorMsg() . " SQL: " . $sql2);

                $sql1 = "UPDATE locations SET StateName ='" . $rs2->fields[0] . "',  combo ='" . $rs->fields[0] . " " . $rs->fields[1] ."' where LocationID =" . $rs->fields[2];
                $rs1 = $conn->Execute($sql1);
                if ($rs1 === false) die('select error: ' . $conn->ErrorMsg() . " SQL: " . $sql1);
                echo $sql1;
            }

            ?>

-------------------解决--------------------------- ---

UPDATE locations 
  JOIN states_cache
    ON states_cache.StateInitials = locations.StateInitials
SET states_cache.StateName = locations.StateName, locations.Combo = CONCAT(locations.City, ' ', locations.StateInitials) 

感谢Marc B指点我更简单的解决方案

1 个答案:

答案 0 :(得分:0)

UPDATE locations 
  JOIN states_cache
    ON states_cache.StateInitials = locations.StateInitials
SET states_cache.StateName = locations.StateName, locations.Combo = CONCAT(locations.City, ' ', locations.StateInitials)