首页 > 解决方案 > 使用 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;

但我想同时列出出发地和目的地,我无法编写查询。有什么帮助吗?

标签: mysqljoin

解决方案


您将需要加入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;

推荐阅读