具有内部连接和两个foreing键的查询表数据

iyfamqjs  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(380)

我有以下两张table:

<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
}
</style>
</head>
<body>

<table>
  <tr>
    <th>airport</th>
  </tr>
  <tr>
    <td>id_airport</td>
  </tr>
  <tr>
    <td>name_airport</td>
  </tr>
</table>

<h4>and</h4>

</body>
</html>

<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
}
</style>
</head>
<body>

<table>
  <tr>
    <th>route</th>
  </tr>
  <tr>
    <td>id_route</td>
  </tr>
  <tr>
    <td>id_airport_origin</td>
  </tr>
  <tr>
    <td>id_airport_destination</td>
  </tr>
</table>

</body>
</html>

route.id\u airport\u origin和route.id\u airport\u destination都是airport.id\u airport的外键
我需要查询与其foreing键匹配的name\u airport列。
我试图执行以下查询,但没有成功。

SELECT route.id.route, airport.name_airport, airport.name_airport
FROM route
INNER JOIN airport ON route.id_airport_origin AND route.id_airport.destination = airport.id_airport

我尝试了以上代码的几种组合,但无法获得正确的查询。
有什么想法吗?

s71maibg

s71maibg1#

您的查询不返回任何行,因为您要查找的机场的id等于这两个值 id_airport_origin 以及 id_airport_destination 路线:显然这不能匹配(。。。除非路线的起点和终点相同)。
insead,您需要两次加入airport表,一次用于起点,另一次用于目的地:

select
    r.id_route,
    ao.name_airport name_airport_origin
    ad.name_airport name_airport_destination
from route r
inner join airport ao on ao.id_airport = r.id_airport_origin
inner join airport ad on ad.id_airport = r.id_airport_destination

相关问题