[英]SELECT sql statement with two different tables and condition
我的数据库中有两个表,就像
部
//Department
D# DNAME
---------------
1 RESEARCH
2 IT
3 SCIENCE
项目
//Project
Budget D#
---------------
22500 1
22300 1
50000 2
所以我用这句话
SELECT D#,DNAME and sum(budget) as total budget
FROM DEPARTMENT,PROJECT
GROUP BY D#;
我的输出应该是,如果一个部门没有任何项目预算,则平均值显示为0
D# DNAME total budget
-------------------------------
1 RESEARCH 44800
2 IT 50000
3 SCIENCE 0
您缺少where
子句:
SELECT d.D#,DNAME and sum(budget) as total budget
FROM DEPARTMENT d, PROJECT p
where d.d# = p.dt#
GROUP BY d.D#;
或包括没有预算的部门:
SELECT d.D#,DNAME and sum(budget) as total budget
FROM DEPARTMENT d
left outer join PROJECT p
on d.d# = p.d#
GROUP BY d.D#;
这可能对您有帮助
SELECT `D#`,`DNAME`,
IFNULL((SELECT sum(`budget`)
FROM `project` WHERE `project.`D#` = `Department`.`D#` ),0) AS `total budget`
FROM `Department`
如果对此查询执行EXPLAIN
,您可能会注意到,与使用GROUP BY
查询相比,它使用索引的效率更高
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.