[英]SQL query for returning multiple fields joined to the same reference
So I have the following table, do_stock_movement, that looks like this: 所以我有下表do_stock_movement,看起来像这样:
stock_movement_id sm_number sm_source_id sm_destination_id 15164b86a7533d 145 1516478840ee29 151644d8bd63f2 15166b89d1a9fc 194 15165c481bd9d0 151659e632cd48
The columns sm_source_id
and sm_destination_id
both reference product points stored in do_product_points
. 列
sm_source_id
和sm_destination_id
都引用存储在do_product_points
产品点。
I'm using the following SQL query: 我正在使用以下SQL查询:
SELECT * FROM do_stock_movement INNER JOIN do_product_points ON product_points_id = sm_source_id WHERE sm_number = '145'
In do_product_points
, there's a field called pp_name
. 在
do_product_points
,有一个名为pp_name
的字段。 I need the corresponding pp_name
for both sm_source_id
and sm_destination_id
. 我需要相应的
pp_name
两个sm_source_id
和sm_destination_id
。
However, the query above will only return the pp_name
for sm_source_id
, or for sm_destination_id
if you change the joined field to that. 但是,上面的查询仅将
pp_name
或pp_name
的sm_source_id
返回,如果您将联接字段更改为sm_destination_id
。
What SQL query will return the corresponding pp_name
for both sm_source_id
and sm_destination_id
? 什么SQL查询将返回相应的
pp_name
两个sm_source_id
和sm_destination_id
?
I hope this is clear. 我希望这很清楚。 Please ask questions if it isn't!
请问是否不是!
JOIN
this table do_product_points
one more times for the sm_destination_id
: 将表
do_product_points
JOIN
一次sm_destination_id
:
SELECT
s.pp_name AS SourcePoint,
d.pp_name AS DestinationPoint,
...
FROM do_stock_movement AS m
INNER JOIN do_product_points s ON s.product_points_id = m.sm_source_id
INNER JOIN do_product_points d ON d.product_points_id = m.sm_destination_id
WHERE m.sm_number = '145'
You need join twice and use alias: 您需要加入两次并使用别名:
SELECT *, Src.pp_name, Dst.pp_name FROM do_stock_movement
INNER JOIN do_product_points as Src
ON Src.product_points_id = sm_source_id
INNER JOIN do_product_points as Dst
ON Dst.product_points_id = sm_destination_id
You need to join to the product_points table twice, once with source_id and once with destination_id: 您需要两次连接到product_points表,一次使用source_id,一次使用destination_id:
SELECT * FROM do_stock_movement move
INNER JOIN do_product_points source ON source.product_points_id = move.sm_source_id
INNER JOIN do_product_points dest ON dest.product_points_id = move.sm_destination_id
WHERE sm_number = '145'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.