MySQL 如何从单个 table 中组织分层数据组?

How do I in MySQL organize groups of hierarchical data from a single table?

我正在尝试创建一个 MySQL 查询来对分层数据进行分组。这是数据库的示例

table name: location
locationID INT UNSIGNED NOT NULL AUTO_INCREMENT,
parentID INT UNSIGNED NOT NULL,
name CHAR(255)

这里是一些示例数据

 locationID    parentID     name
 1      |     0     |   United States
 2      |     1     |   Massachusetts
 3      |     2     |   Boston
 4      |     2     |   Worcester
 5      |     1     |   New York
 6      |     5     |   Brooklyn
 7      |     1     |   Colorado
 8      |     7     |   Denver
 9      |     0     |   Canada
 10     |     9     |   Ontario
 11     |     10    |   Toronto
 12     |     9     |   Quebec
 13     |     12    |   Quebec City

以上名称只是示例,以了解我希望如何处理查询。 我希望以特定方式显示上述 table 数据。 我希望 parentID = 0 的行按名称升序(国家/地区)排序,并在每一行下列出 parentID 与 locationID (states/provinces) 匹配的行,并在每一行下列出 parentID 匹配的行locationID(城市)。

这是我迄今为止尝试过的方法,但无济于事。

SELECT locationID,parentID,name FROM location ORDER BY parentID ASC name ASC

以及

SELECT locationID,parentID,name FROM location GROUP BY 'parentID' ORDER BY name ASC

我希望能够添加行并选择一个父项并生成一个列表,其中父项在最上面,然后是下面的子项以及每个子项下面的子项的子项,等等。我正在编程 MySQL 和 PHP

任何解决此问题的建议都将非常有帮助和感激,在此先感谢。

我建议您的数据库设计是错误的,因此很难根据需要查询数据以便根据需要对其进行格式化。

考虑三个表:

Country with columns:- name,country_ID
State with columns:- name, state ID, country ID
City with columns:- name, city_ID (maybe not needed) state_ID.

通过这种设计,查询几乎可以与您对话。

create table location
(
    id int auto_increment primary key,
    parentId int not null, -- avoid nulls, 0 is top-level
    place varchar(100) not null
);

insert location(parentId,place) values (0,'Canada'),(0,'Mass'),(0,'Jersey');

insert location(parentId,place) values (2,'Boston'),(2,'Newton'),(2,'Woods Hole');

insert location(parentId,place) values (5,'Chestnut Hill');

insert location(parentId,place) values (3,'Montclair'),(3,'Secaucus');


-- get first level children
select t1.*,t2.*
from location t1
join location t2
on t2.parentId=t1.id and t1.place='Mass'