mysql - 使用 mysql 和许多外键加入多个表
问题描述
使用 MySQL,我有 3 个表,如下所示:
locations (id, name)
products(id, description)
inventory_records(id, product_id, move_from, move_to)
product_id
是产品的 FK ;move_from
并且是对位置move_to
的 FK 。
以下查询列出了所有产品名称及其来源。
select
products.description,
locations.name
from
inventory_records
inner join products on
products.id = inventory_records.product_id
inner join locations on
locations.id = inventory_records.move_from
limit 10;
但我想同时列出出发地和目的地,我无法编写查询。有什么帮助吗?
解决方案
您将需要加入locations
表两次。首次加入将开启move_from
;并且第二个表连接将打开move_to
。
另外,请注意,在多表查询的情况下使用别名是一种很好的做法,以提高代码清晰度、可读性和明确的行为。
SELECT
products.description,
lfrom.name AS move_from_location,
lto.name AS move_to_location
FROM
inventory_records
INNER JOIN products ON
products.id = inventory_records.product_id
INNER JOIN locations AS lfrom ON
lfrom.id = inventory_records.move_from
INNER JOIN locations AS lto ON
lto.id = inventory_records.move_to
LIMIT 10;
推荐阅读
- vue.js - Vue 3 - 数字 0 增加 (++) 在模板中不是 1 而是 101,为什么?
- python-3.x - 班级列表 - 我将如何重复输入的学生数量?
- winapi - WaitOnAddress / WakeByAddressAll / WakeByAddresSingle 如何工作
- reactjs - 如何在渲染执行后使用计时器更新 UI
- python - 使用需要登录的 Beautiful Soup 抓取网站
- c - ARM NEON 数组类型有什么好处(除了方便)吗?
- ssh - 在 ipv6 上获取 `ssh client_loop: send disconnect: Broken pipe`
- android - 为什么在使用 kotlinx.android.parcel.Parcelize 时会收到“未实现抽象成员”警告?
- php - ImageMagick 支持的格式数量:0
- python - 如何在字符串中随机大写字符?