1

我有 4 张桌子:

  • ARTICOLE
  • BAR
  • BUCATARIE
  • MAGAZIE

mysql>select * from ARTICOLE;

| OID | ART      |  
|   1 | TEST     |
|   2 | TESTQ    |
|   3 | MYART    |
|   4 | MYARTBUC |

4 行一组(0.00 秒)

mysql>select * from BAR;

| OID | ART   | CANT     |
|   1 | TEST  |  3.00000 |
|   2 | TESTQ |  1.00000 |
|   3 | MYART | 20.00000 |

3 行一组(0.00 秒)

mysql>select * from BUCATARIE;

| OID | ART      | CANT     |
|   1 | TEST     |  5.00000 |
|   2 | MYARTBUC | 10.00000 |

2 行(0.00 秒)

mysql>select * from MAGAZIE; 空集(0.00 秒)

下面的查询

mysql>select a.ART,sum(bar.CANT),sum(buc.CANT),sum(mag.CANT) from ARTICOLE a,BUCATARIE buc,BAR bar,MAGAZIE mag where a.ART=bar.ART and a.ART=bar.ART and a.ART=mag.ART group by a.ART;

返回:


空集(0.00 秒)

必须如何查询才能返回:

| ART | sum(bar.CANT) | sum(buc.CANT) | sum(mag.CANT) |
TEST  |  3.00000 | 5.00000 | NULL |
TESTQ |  1.00000 | NULL | NULL |
MYART | 20.00000 | NULL | NULL|
MYARTBUC | NULL | 10.00000 | NULL |

???

任何帮助表示赞赏。

4

1 回答 1

1

您需要使用LEFT JOIN包含来自其他表的结果而不过滤掉不匹配的记录:

   select a.ART,sum(bar.CANT),sum(buc.CANT),sum(mag.CANT)
     from ARTICOLE a
left join BUCATARIE buc on buc.ART = a.ART
left join BAR bar on bar.ART = a.ART
left join MAGAZIE mag on mag.ART = a.ART
group by a.ART;

样本结果:

ART         SUM(BAR.CANT)   SUM(BUC.CANT)   SUM(MAG.CANT)
MYART       20      
MYARTBUC                    10  
TEST        3               5   
TESTQ       1       

演示:http ://www.sqlfiddle.com/#!2/6efb2/2

于 2012-04-27T14:48:12.987 回答