我下载了一个数据库表,里面有世界上几乎所有的国家和城市。
表显示如下:
location_id -> Name -> location_type -> parent_id
location_type为位置类型,0代表国家,1代表城市。
parent_id是当位置为城市时来自国家的id。
我想这样为用户显示数据:
城市、国家名称。
Ex: Lisbon, Portugal
并使用Json打印
你们能帮我建立这个查询吗?
我查询:$locations = mysqli_query($con, "SELECT name, location_id, parent_id FROM location WHERE location_type = 1 ");
$locarray = array();
while ($row = mysqli_fetch_assoc($locations))
{
$locarray[] = $row;
}
如您所见,我只显示城市,我想从城市中获取parent_id,并打印城市所在国家的名称。
谢谢。
试试这个
SELECT c2.name,c1.name, c1.location_id, c1.parent_id
FROM
location c1 join location c2 on c1.`parent_id`=c2.`location_id`
WHERE c1.location_type = 1