我有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 |
????
任何帮助表示感谢。
答案 0 :(得分: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