使用MySQL,我有3个表,如下所示:
locations (id, name)
products(id, description)
inventory_records(id, product_id, move_from, move_to)
product_id
是产品的FK; move_from
和move_to
代表位置。以下查询列出了所有产品名称及其来源。
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
上。
另外,请注意,在多表查询的情况下,为了代码清晰,易读且行为明确,最好使用Aliasing。
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;