database - 表 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
它确实返回了两个电影名称,但是在两个不同的行中,我只想返回一行,因为我希望在该行中返回更多信息,例如名称可能是价格或任何其他列。
解决方案
你很接近,诀窍是使用别名来引用每个连接上的表,这应该有效:
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
推荐阅读
- vue.js - Bootstrap-vue 动态吐司不起作用
- c# - 自动映射公历日期时间到波斯日期时间
- python - 如何在python中拆分二元组?
- amazon-web-services - 尝试连接到 ec2 时,云端显示“无法满足请求 502 错误”
- html - div 的第二个子元素应保持不变
- haskell - 你可以使用 `fromIntegral` 来解决这种类型的错误吗?
- node.js - 在 Windows 服务器上托管 nodejs 的最佳(安全)方式
- html - 如何在 Web 视图中以表格形式对齐数据,在移动视图中以列表形式对齐数据?
- java - Mockito 只能模拟非私人和非最终课程
- vb6 - 从 DLL res 文件中将希伯来语字符串读入 VB6