2014-02-28 48 views
0

我已经下面的查询给我什么,我wan't(见table_entrees)只能加入一个表中的列与另一个表

SELECT designation, ref1, ref2, ref3, sum(a.qte) AS TotalQte 
FROM table_entrees a 
WHERE a.ref1 = 'VT2' 
GROUP BY a.designation, a.ref1, a.ref2, a.ref3 

table_entrees:

designation ref1 ref2 ref3 TotalQte 
VT   VT2  GRIS L  150 
VT   VT2  GRIS XL  150 
VT   VT2  Jaune L  150 
VT   VT2  Jaune XL  150 

和另一个查询相同的第一个,但对于另一个表

SELECT designation, ref1, ref2, ref3, sum(b.qte) AS TotalQte2 
FROM table_sorties b 
WHERE a.ref1 = 'VT2' 
GROUP BY b.designation, b.ref1, b.ref2, b.ref3 

table_sorties:

designation ref1 ref2  ref3 TotalQte2 
VT   VT2 GRIS  L  62 
VT   VT2 JAUNE  L  15 

但问题是,我已经试过就像下面的表格,它检查是否REF1,REF2,table_sorties的REF3在table_entrees存在两者之间的结合,然后显示出它的结果还显示TotalQte2 0

designation ref1 ref2 ref3 TotalQte  TotalQte2 
VT   VT2  GRIS L  150   62 
VT   VT2  GRIS XL  150   0 
VT   VT2  Jaune L  150   15 
VT   VT2  Jaune XL  150   0 

我试过以下查询,但没有给出预期的结果!

SELECT 
    a.designation, 
    a.ref1, 
    a.ref2, 
    a.ref3, 
    sum(a.qte) AS TotalQte, 
    sum(b.qte) AS TotalQte2 
FROM FROM table_entrees a,table_sorties b 
WHERE a.ref1 = 'VT2' 
GROUP BY a.designation, a.ref1, a.ref2, a.ref3 
+0

你有可以加入表格的ID列或唯一标识符吗? –

回答

0

使用每个查询作为子查询,并使用left outer join

SELECT q1.designation, q1.ref1, q1.ref2, q1.ref3, q1.TotalQte, 
     coalesce(q2.TotalQte2, 0) as TotalQte2 
FROM (SELECT designation, ref1, ref2, ref3, sum(a.qte) AS TotalQte 
     FROM table_entrees a 
     WHERE a.ref1 = 'VT2' 
     GROUP BY a.designation, a.ref1, a.ref2, a.ref3 
    ) q1 LEFT JOIN 
    (SELECT designation, ref1, ref2, ref3, sum(b.qte) AS TotalQte2 
     FROM table_sorties b 
     WHERE a.ref1 = 'VT2' 
     GROUP BY b.designation, b.ref1, b.ref2, b.ref3 
    ) q2 
    on q1.designation = q2.designation and 
     q1.ref1 = q2.ref1 and 
     q1.ref2 = q2.ref2 and 
     q1.ref3 = q2.ref3; 

当你做对的聚集加盟之前,你从两个qte领域的所有组合的笛卡尔乘积表。通常,笛卡尔产品上的sum()将不正确。

+0

@ 0x58。 。 。 “加入”条件中存在拼写错误。它应该现在正确工作。 –

+0

ouh好,谢谢你纠正它。 – 0x58

0

基本上你想要在三个ref列上做一个左连接,如前面的答案所述。

当您执行左连接B时,表A中的所有列都将保留。如果表B中没有相应的条目,则它将显示为空。

相关问题