加入3表与1个以上的关系

时间:2016-01-19 06:41:07

标签: mysql join

mtOrder
-------
idOrder idCust
1       123423      
2       324602

dtOrderBox
----------
idOrder     idBox    idItem   Quantity  usedBox
1           1        39       2         1
1           2        34       30        0
1           3        39       2         1
2           1        39       10        1
2           2        24       5         0

dtOrderDetail
-------------
idOrder    idBox     idItem  Quantity
1          1         45      10
1          3         46      10
2          1         45      15

如上图所示,由idOrderdtOrderBox以及dtOrderDetail关联的3表也由idBox再次链接。 dtOrderBox用于记录框,也用于不带框的项目。 dtOrderDetail用于记录在dtOrderBox中订购的Box的内容。

问题在于,当我试图一起加入这个树表时

select * from mtOrder
Join dtOrderBox on dtOrderBox.idOrder = mtOrder.idOrder
Join dtOrderDetail on dtOrderDetail.idOrder = mtOrder.idOrder and dtOrderDetail.idBox = dtOrderBox.idBox

使用它,结果将显示dtOrderBox中使用Box的所有项目。不使用框的项目(如dtOrderBoxusedBox中所示)将不会显示。 谢谢你的帮助!

Desired Result
--------------
idOrder   idBox   idItem Quantity
1         1       45     20
1         2       34     30 
1         3       46     20
2         1       45     150
2         2       24     5

4 个答案:

答案 0 :(得分:0)

尝试此查询: -

var3

答案 1 :(得分:0)

尝试使用左连接:

select mtOrder.idOrder, mtOrder.idCust, 
      dtOrderBox.idItem, dtOrderBox.Quantity, dtOrderBox.usedBox, 
      dtOrderDetail.Quantity 
from mtOrder
Left Join dtOrderBox on dtOrderBox.idOrder = mtOrder.idOrder
Left Join dtOrderDetail on dtOrderDetail.idOrder = mtOrder.idOrder and dtOrderDetail.idBox = dtOrderBox.idBox

答案 2 :(得分:0)

使用左连接来保留dtOrderBox表中与任何内容不匹配的记录。

SELECT m.*, dob.*, dod.*
FROM mtOrder m
LEFT JOIN dtOrderBox dob
    ON dob.idOrder = m.idOrder
LEFT JOIN dtOrderDetail dod
    ON dod.idOrder = m.idOrder AND dod.idBox = dob.idBox

答案 3 :(得分:0)

试试这个:

SELECT mo.*,dob.*,dod.* 
FROM mtOrder as mo
LEFT JOIN dtOrderBox as dob ON mo.idOrder = dob.idOrder
LEFT JOIN dtOrderDetail as dod ON dod.idBox = dob.idBox and dod.idBox = dob.idBox