문제

In my Firebird database I have two tables, in the first one (LOCATIONS) I keep info about some locations (like in RPG game), which is very simple and looks like this:

NAME
Location 1
Location 2
Location 3
Location 4
Location 5

and the second table (CONNECTIONS) connects this locations so I know where I can go from which location. The case is that every row connects two locations in only one direction so if I want to create two-way connection I have to insert two rows into CONNECTIONS table.

Some example connections:

first_location|second_location
  Location 1  |  Location 2 
  Location 1  |  Location 3
  Location 2  |  Location 1
  Location 2  |  Location 4
  Location 3  |  Location 1
  Location 3  |  Location 4
  Location 4  |  Location 5
  Location 5  |  Location 1

As you can see, these connections are representation of some directed graph.

I need to create a SQL query that will show me all locations (graph nodes) to which I can go from given loc/node and in additional, whether or not I can come back to the previous node. The first part is easy, because

select second_location 
from connections 
where connections.first_location = 'Location 1'

gives me all nodes that are connected to Location 1, but the problem starts when I try to get info about bidirectionality of this connections.

so far I've tried something like this:

select c.first_location as first, c.second_location as second, p.count
from connections as c
where c.first = 'Location 1' 
inner join (
    select count(*) 
    from connections 
    where connections.first_location = c.second 
    and connections.second_location = 'Location 1'
) as p

and I hoped to get result like this:

   first   |   second   | count
Location 1 | Location 2 |   1
Location 1 | Location 3 |   0

but i was wrong. What should I do to solve this problem?

도움이 되었습니까?

해결책

As originally posted in the question by the TS:

I don't need help anymore, somehow I solved this problem right after I posted this question.

SELECT p.first_location, p.second_location, (
    SELECT COUNT (*)
    FROM (
        SELECT q.first_location, q.second_location 
        FROM connections AS c 
        WHERE p.first_location = q.second_location 
        and p.second_location = q.forst_location
    ) 
)
FROM connections AS p 
WHERE p.first_location = 'Location 1'

다른 팁

You can solve this with a self JOIN:

SELECT fwd.first, fwd.second, bck.first IS NOT NULL returnable
  FROM connections fwd LEFT JOIN connections bck
    ON (fwd.first=bck.second AND fwd.second=bck.first)

http://sqlfiddle.com/#!12/ec191/13/0

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top