从表中的同一列中获取多个值

时间:2015-06-05 04:15:40

标签: mysql sql

我有2张桌子。一个列出所有对象(对象),另一个包含对象层次结构(层次结构)。

Object table:
ID   | Description | ClassID
------------------------------
0001 | Room 1A     | 1000
0002 | Floor 1     | 1001
0003 | Room 1B     | 1000
0004 | Building 01 | 1002

其中classID指定对象的类型(room = 1000,floor = 1001或building = 1002)

Hierarchy table:
RelationID | parentid | child ID | level
1          | 0004     | 0002     |   1
2          | 0004     | 0001     |   2
3          | 0002     | 0001     |   1

其中level指定子级的层次级别。例如。如果我正在搜索所有建筑物(1 - >儿童(地板),2 - >孙子(房间))。

所以我想从对象表中获取所有房间,地板和他们所在建筑物的描述。

E.g。

Room | Floor | Bldg
-------------------
1A   |   1   |  01
1B   |   1   |  01
2A   |   2   |  01
2B   |   2   |  01
1A   |   1   |  02

等。 我怎么能这样做呢?

2 个答案:

答案 0 :(得分:1)

您可以使用此类查询来获取数据:

SELECT Room.Description as Room, Floor.Description as Floor, Buildings.Description as Bldg
FROM ObjectTable Buildings 
    INNER JOIN Hierarchy BuildingFloor ON Buildings.ID = BuildingFloor.ParentId AND BuildingFloor.level = 1
    INNER JOIN ObjectTable Floor ON BuildingFloor.ChildId = Floor.ID
    INNER JOIN Hierarchy FloorRoom ON Floor.ID = FloorRoom.ParentId AND FloorRoom.level = 2
    INNER JOIN ObjectTable Room ON FloorRoom.ChildId = Room.ID
WHERE Buildings.ClassID = 1002 AND Floors.ClassID=1001 AND Rooms.ClassID =1000

我不完全了解您使用level字段的位置和方式,因此可能不需要此部分查询

答案 1 :(得分:0)

您可以多次加入ObjectTableHierarchyTable

SELECT B.Description, F.Description, R.Description
FROM ObjectTable B
    INNER JOIN HierarchyTable HT1
        ON B.ID = HT1.parentid
    INNER JOIN ObjectTable F
        ON F.ID = HT1.childid
    INNER JOIN HierarchyTable HT2
        ON HT1.childid = HB2.parentid
    INNER JOIN ObjectTable R
        ON R.ID = HT2.childid
WHERE B.ClassID = 1002
    AND F.ClassID=1001
    AND R.ClassID =1000
    AND HT1.level = 1
    AND HT2.level = 1

修改

只需要过滤Level = 1。当我们遍历孩子到孩子时,不需要来自层次结构的孙子记录