反復的な SQL クエリ (これは廃止する必要があります)の問題を解決するのに問題があり、別の方法を模索しています。
(また、残念ながら、AJAXはあまり適していません)
位置データ用に次のテーブルがあるとします。
Country
country_id
name
State
state_id
country_id
name
City
city_id
state_id
name
今、私はすべてのデータを取得しようとしていますが、実際には非常に小さい ( 147 の都市、64 の州に分割、2 つの国に分割) ですが、繰り返しループしているため、永遠に時間がかかります:
// this is pseudo-code, but it gets the point across
$countries = getCountries();
foreach($countries as &$country){
$country['states'] = $states = getStates($country['country_id']);
foreach($states as &$state){
$state['cities'] = getCities($state['state_id']);
}
}
このようにする理由は、最終的な結果セットが次の形式である必要があるためです。
$countries = array(
array(
'name' => 'country_name',
'id' => 'country_id',
'states' => array(
array(
'name' => 'state_name',
'id' => 'state_id',
'cities' => array(
array(
'name' => 'city_name',
'id' => 'city_id',
),
// ... more cities
),
),
// ... more states
),
),
// ... more countries
);
より速いアプローチに頭を悩ませることはできないようです。階層データのクエリに代わるものは何ですか?
改訂:
$sql = "SELECT
`dbc_country`.`name` as `country_name`,
`dbc_state`.`name` as `state_name`,
`city_id`,
`dbc_city`.`name` as `city_name`,
`latitude`,
`longitude`
FROM
`dbc_city`
INNER JOIN
`dbc_state` ON `dbc_city`.`state_id` = `dbc_state`.`state_id`
INNER JOIN
`dbc_country` ON `dbc_state`.`country_id` = `dbc_country`.`country_id`";
$locations = array();
foreach($datasource->fetchSet($sql) as $row){
$locations[$row['country_name']][$row['state_name']][] = array(
$row['city_id'],
$row['city_name'],
$row['latitude'],
$row['longitude'],
);
}
(州/国の値も削除しましid
た。無駄にスペースを占めていたからです)