使用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;
但是我想同时列出起点和终点,但我无法列出查询。有帮助吗?
答案 0 :(得分:0)
您将需要两次连接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;