编码国家的更好方法>区域>市

时间:2018-05-26 22:26:33

标签: php

我正在寻找编写此脚本的更好方法。 事实上,这可以按预期工作,但我希望优化查询,如果可能的话。

我有一个简单的数据库,如下所示:

COUNTRY
country_id
country_name

REGION
region_id
region_country_id
region_name

CITY
city_id
city_region_id
city_name

我有这样的输出:

USA
 - NEW YORK
   -- NEW YORK
   -- BUFFALO
   -- etc,

并使用此脚本获取列表:

                        $query_country = " SELECT country_id, country_name FROM country GROUP BY country_name ";
                        $result_query_country = mysqli_query($mysqli,$query_country) or die(mysqli_error($mysqli));
                        while($row = mysqli_fetch_array($result_query_country)) {
                            $country_id = $row['country_id'];
                            $country_name = $row['country_name'];

                            $query_region = " SELECT region_id, region_name FROM region WHERE region_country_id = $country_id GROUP BY region_name ";
                            $result_query_region = mysqli_query($mysqli,$query_region) or die(mysqli_error($mysqli));

                            echo '<b>'.$country_name.'</b>';
                            echo '<br>';

                            while($row = mysqli_fetch_array($result_query_region)) {
                                $region_id = $row['region_id'];
                                $region_name = $row['region_name'];

                                $query_city = " SELECT city_id, city_name FROM city WHERE city_region_id = $region_id";
                                $result_query_city = mysqli_query($mysqli,$query_city) or die(mysqli_error($mysqli));

                                echo $region_name;
                                echo '<br>';

                                while($row = mysqli_fetch_array($result_query_city)) {
                                    $city_id = $row['city_id'];
                                    $city_name = $row['city_name'];

                                    echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$city_name;
                                    echo '<br>';
                                }
                            }
                            echo '<br>';
                        }

1 个答案:

答案 0 :(得分:1)

您可以将其合并为一个查询:

$query = <<<end
    select distinct country_id, country_name, region_id, region_name, city_id, city_name
    from country, region, city
    where region.region_country_id = country.country_id
        and city.city_region_id = region.region_id
end;

$result = $db->query($query) or die($db->error);

while ($row = $result->fetch_assoc()) {
    printf(
        '<b>%s</b><br>&nbsp;&nbsp;&nbsp;%s<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp%s<br>',
        htmlspecialchars($row['country']),
        htmlspecialchars($row['region']),
        htmlspecialchars($row['city'])
    );
}