多表查询 left join

很久很久没写SQL了,今天遇到,居然不知道怎么下手,请教了下同事,问题解决,记录下来。

同一个表有两个相同类型的字段引用同一个表的主键。

迁移记录表 ams_migrate

字段名称

字段类型

描述

migrate_id

Long

PK

current_position

Long

当前位置FK 关联depot_id

origin_position

Long

原始位置FK 关联depot_id

 

 

 

 

 

 

 

仓库记录表 asm_depot

字段名称

字段类型

描述

depot_id

Long

PK

depot_name

varchar

仓库名称

groupid

Long

基地位置FK

 

基地记录表 sm_groups

字段名称

字段类型

描述

groupid

Long

PK

name

varchar

基地名称

 



SQL查询每条迁移记录 的 原始仓库 原始基地,当前仓库,当前基地

SELECT t2.depot_name AS originalDepot,t4.`name` AS originalGroup,t3.depot_name as currentDepot,t5.`name` AS currentGroup 
FROM asm_migrate t1 
LEFT JOIN asm_depot t2 ON t1.original_position=t2.depot_id 
LEFT JOIN asm_depot t3 ON t3.depot_id=t1.current_position
LEFT JOIN sm_groups t4 ON t4.groupid=t2.groupid
LEFT JOIN sm_groups t5 ON t5.groupid=t3.groupid
原文地址:https://www.cnblogs.com/hanleytang/p/SQL.html