通过另一个表从一个表中获取彼此相关的行

时间:2012-01-08 21:15:47

标签: mysql sql

我有两张桌子:

    COUNTRY
    -------------
    id
    name

    NEIGHBOUR
    -------------
    id
    id_country1
    id_country2

id_country1id_country2是表COUNTRY中与彼此相关的国家/地区的ID。

如何制作一个精选语句,以便获取与某个特定国家/地区相邻的所有国家/地区的名称?

1 个答案:

答案 0 :(得分:1)

SELECT
  COUNTRY.name AS name
FROM
  NEIGHBOUR
  INNER JOIN COUNTRY ON
    NEIGHBOUR.id_country1=COUNTRY.id
    OR NEIGHBOUR.id_country2=COUNTRY.id 
WHERE
    (NEIGHBOUR.id_country1=<your requested id>
    OR NEIGHBOUR.id_country2=<your requested id>)
    AND COUNTRY.id<><your requested id>