首页 > 解决方案 > 表 A 中的两列包含存储在不同表 B 中的 id 如何选择和获取存储在表 B 中的数据?

问题描述

我有 2 个表,表 A 有 2 个包含 id 的列,表 B 具有与电影名称匹配的 id。我想选择电影名称而不是电影 ID 的行,例如

表 A

+-----+----------------------------------------------+
| id  | name   | favmovieid|   leastfavmovieid       |
+-----+----------------------------------------------+
| 101 | Name 1 |     1     |          5              |
| 102 | Name 2 |     6     |          8              |
| 103 | Name 3 |     8     |          6              |
+-----+----------------------------------------------+

表 B

+-------+---------------------+
| movid | namemovie           |
+-------+---------------------+
|  1    | Harry Potter 1      |
|  2    | Harry Potter 2      |
|  3    | Harry Potter 3      |
|  4    | Lord of the Rings 1 |
|  5    | Lord of the Rings 2 |
|  6    | Lord of the Rings 3 |
|  7    | Iron Man 1          |
|  8    | Iron Man 2          |
+-------+---------------------+

我试图通过内部连接两个列来使用内部连接,例如

Select TableB.namemovie,TableB.namemovie from 
((TableA inner join TableB on TableA.favmovieid=TableB.movid) inner join on TableB TableA.leastfavmovieid=TableB.movid) where TableA.id=101

但我收到一个错误,说表 B 被提及太多次

然后我也尝试了 union as

Select TableB.namemovie from (TableA inner join TableB on TableA.favmovieid=TableB.movid)
where TableA.id=101
union 
Select TableB.namemovie from (TableA inner join TableB on TableA.leastfavmovieid=TableB.movid)
where TableA.id=101

它确实返回了两个电影名称,但是在两个不同的行中,我只想返回一行,因为我希望在该行中返回更多信息,例如名称可能是价格或任何其他列。

标签: databasepostgresql

解决方案


你很接近,诀窍是使用别名来引用每个连接上的表,这应该有效:

select b1.namemovie,b2.namemovie from TableA 
inner join TableB b1 on TableA.favmovieid=b1.movid 
inner join TableB b2 on TableA.leastfavmovieid=b2.movid
where TableA.id=101

推荐阅读