使用 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;