Mysql 递归选择表

Mysql 递归选择表,mysql,tsql,Mysql,Tsql,现在我需要在MySQL中创建一个表的视图,表的基本结构如下: create table mirror ( ID varchar(50) not null primary key, PARENT_ID varchar(50) not null comment 'The id of its parent', CODE varchar(50) null comment 'Code of t

现在我需要在MySQL中创建一个表的视图,表的基本结构如下:

create table mirror (
    ID                varchar(50)    not null primary key,
    PARENT_ID         varchar(50)    not null comment 'The id of its parent',
    CODE              varchar(50)    null comment 'Code of the component',
    NAME              varchar(500)   null comment 'Name of the component',
    UNIT              varchar(100)   null comment 'Unit of the component'
)
现在,该视图用于选择同一表中的所有子级,您可以看到该表的pic:

如您所见,大锤子、小锤子、小锤子应该是锤子的子项,这与扳手相同,现在视图将获取第1行和第5行的数据,然后添加一个单元格来写入它们的子项,如“SP0001、SP0002、SP0003”

如何创建此视图


谢谢你的帮助

对于此示例数据,您需要一个自联接,然后使用
GROUP\u CONCAT()
收集每个父级的所有子级:

SELECT m1.ID, m1.CODE,
       GROUP_CONCAT(m2.CODE) children
FROM mirror m1 LEFT JOIN mirror m2
ON m2.PARENT_ID = m1.ID
WHERE m1.PARENT_ID = 0
GROUP BY m1.ID, m1.CODE

对于此示例数据,您需要一个自联接,然后使用
GROUP\u CONCAT()
收集每个父级的所有子级:

SELECT m1.ID, m1.CODE,
       GROUP_CONCAT(m2.CODE) children
FROM mirror m1 LEFT JOIN mirror m2
ON m2.PARENT_ID = m1.ID
WHERE m1.PARENT_ID = 0
GROUP BY m1.ID, m1.CODE