使用5个不同的表加入查询

时间:2016-07-11 02:10:52

标签: sql firebird

tbl_vehicle_mst
--------------------------
v_id    v_no    v_make
1   Bus-01      Tata
2   Bus-02      Volvo
3   Bus-03      Tatra

tbl_route_mst
--------------------------------
r_id    r_no    r_from  r_to
1       01      A       B
2       02      A       C
3       03      A       D

tbl_vehicle_route_map
-----------------------------
vrm_id  r_id    v_id    
1       1       2
2       2       1


tbl_driver_mst
-------------------------------
d_id    d_code      d_name
1       drv-1       John
2       drv-2       Ram
3       drv-3       Gomesh

tbl_veh_driver_map
------------------------------
vem_id   v_id   d_id
1        1      2
2        2      3

我有5个表,如上所示。使用某种连接查询我希望输出如下所示。由于涉及5个不同的表格;我很困惑,因为如何达到所需的输出。每次我坐下来编写连接查询时,一切都在我头脑中混淆,我感到困惑,无法编写连接查询。我非常有责任向任何指出我正确方向的人提供一些示例sql查询。提前谢谢。

必需的输出

route       v_no        driver_name
------------------------------------
A to B      Bus-02      Gomesh
A to C      Bus-01      Ram 

以下我已尝试过目前

SELECT 
(SELECT b.d_name FROM tbl_veh_driver_map a, tbl_driver_mst b WHERE a.d_id = b.d_id) AS DRIVER_NAME,
(SELECT DISTINCT(b.r_from || ' - ' || b.r_to) AS RT FROM tbl_veh_driver_map a,tbl_route_mst b,tbl_veh_route_map c WHERE a.v_id = c.v_id AND c.r_id = b.r_id) AS ROUTE,
(SELECT a.v_no FROM tbl_vehicle_mst a,tbl_veh_driver_map b WHERE a.v_id = b.v_id) AS v_no,
FROM tbl_veh_driver_map

1 个答案:

答案 0 :(得分:1)

除非我错过了某些东西,否则这看起来就像pk / fk对上的连接一样简单。下面的查询应该为您提供所需的结果:

select 
  r_from || ' - ' || r_to as route, 
  v_no, 
  d_name as driver_name
from tbl_route_mst as r
join tbl_vehicle_route_map as rm on rm.r_id = r.r_id
join tbl_vehicle_mst as v on v.v_id = rm.v_id
join tbl_veh_driver_map as vd on vd.v_id = v.v_id
join tbl_driver_mst as d on d.d_id = vd.d_id