简体   繁体   中英

multiple level parent-child in same mysql table

Although I've found several posts on the subject, I haven't quite come up with an answer that I can relate. Most of the mysql queries I use are fairly simple, so I may just not be following. Anyhow, I would appreciate some assistance.

I have a table of items: buildings, floors, rooms and jacks. Each jack is a child of a room, each room a child of a floor, etc.

I'd like to be able to list, all children (floors), and all children of children, such that I have a table sorted by floor, room, jack for a given building.

Is this possible without getting too complex?

CREATE TABLE items ( ObjectID int(11) NOT NULL, ObjectType varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, ObjectName varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, OwnerId int(11) DEFAULT NULL )

Sample data:
1,building,my hall,NULL
2,floor,FL1,1
3,floor,FL2,1
10,room,RM101,2
11,room,RM102,2
12,room,RM201,3
12,room,RM202,3
51,jack,C101-1,2
52,jack,D202-1,12
53,jack,D102-1,11

Proposed query result:

my hall, FL1, RM101, C101-1

my hall, FL1, RM102,D102-1

my hall, FL2, RM201,

my hall, FL2, RM202,D202-1

Please try this is http://sqlfiddle.com .

CREATE TABLE items (  
  ObjectID int(11) NOT NULL,
  ObjectType varchar(50) DEFAULT NULL,
  ObjectName varchar(50) DEFAULT NULL,
  OwnerId int(11) DEFAULT NULL );

insert into items values(1,'building','my hall',NULL);
insert into items values(2,'floor','FL1',1);
insert into items values(3,'floor','FL2',1);
insert into items values(10,'room','RM101',2);
insert into items values(11,'room','RM102',2);
insert into items values(12,'room','RM201',3);
insert into items values(13,'room','RM202',3);
insert into items values(51,'jack','C101-1',10);
insert into items values(52,'jack','D202-1',13);
insert into items values(53,'jack','D102-1',11);

Query:

select distinct I1.ObjectName AS building,
            i2.ObjectName as floor,
            i3.ObjectName as room,
            i4.ObjectName as jack
from Items I1 
inner join Items i2 on I1.Objectid = i2.ownerId and I1.ObjectType = 'building' and i2.ObjectType = 'floor'
inner join Items i3 on i2.Objectid = i3.ownerId and i2.ObjectType = 'floor' and i3.ObjectType = 'room'
 left join Items i4 on i3.Objectid = i4.ownerId and i3.ObjectType = 'room' and i4.ObjectType = 'jack'
order by I1.ObjectName,i2.ObjectName,i3.ObjectName,i4.ObjectName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM