SQLite查询获取相应的数据

时间:2017-12-12 10:39:35

标签: sql sqlite join

我有一些数据库表可以容纳房间,另一个表格可以容纳那些房间的出口:

房间表:

+---------------+----------------+----------------+
| uid (integer) | name (varchar) | area (varchar) |
+---------------+----------------+----------------+

退出表格:

+------------+---------+-------+
| direction  | fromuid | touid |
+------------+---------+-------+

每个房间有6个可能的方向:北,南,西,东,上,下

我希望从当前uid获取所有uid到3个深度的所有方向。

我的意思是:例如北室的北室和那个北室和那个北室也是。

         |n3|                    |u3|
         |n2|                    |u2|
         |n1|                    |u1|
|w3|w2|w1|  |e1|e2|e3|    and
         |s1|                    |d1|
         |s2|                    |d2|
         |s3|                    |d3|

像这样我希望用n1,n2,n3等键获取所有房间uid

一个查询可以吗?

另请注意,某些方向没有3个房间。例如,东方向只能有一个房间或其他方向,但根本没有任何空间

1 个答案:

答案 0 :(得分:0)

可能这就是你想要的:

select  rooms.uid           as origin,
        exits1.direction    as direction1,
        exits1.touid        as room1,
        exits2.direction    as direction2,
        exits2.touid        as room2,
        exits3.direction    as direction3,
        exits3.touid        as room3
    from rooms
    left outer join exits exits1
        on rooms.uid = exits1.fromuid
    left outer join exits exits2
        on exits1.touid = exits2.fromuid
    left outer join exits exits3
        on exits2.touid = exits3.fromuid

这不是在开始方向上过滤所以如果第二个北室连接到一个房间,你就会得到它。或者如果一个房间有多个连接。要过滤起始方向,请使用以下方法:

select  rooms.uid           as origin,
        exits1.direction    as direction1,
        exits1.touid        as room1,
        exits2.direction    as direction2,
        exits2.touid        as room2,
        exits3.direction    as direction3,
        exits3.touid        as room3
    from rooms
    left outer join exits exits1
        on rooms.uid = exits1.fromuid
    left outer join exits exits2
        on exits1.touid = exits2.fromuid
        and exits1.direction = exits2.direction
    left outer join exits exits3
        on exits2.touid = exits3.fromuid
        and exits2.direction = exits3.direction