SELECT sql语句有两个不同的表和条件

时间:2014-04-26 10:07:50

标签: mysql sql oracle

在我的数据库中有两个表,它就像

//Department
D#      DNAME
---------------
1      RESEARCH
2        IT
3       SCIENCE

PROJECT

//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

2 个答案:

答案 0 :(得分:1)

您错过了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#;

答案 1 :(得分:0)

这可能对您有所帮助

   SELECT `D#`,`DNAME`, 
   IFNULL((SELECT sum(`budget`) 
          FROM `project` WHERE `project.`D#` = `Department`.`D#` ),0) AS `total budget` 
   FROM `Department`

如果对此查询执行EXPLAIN,您可能会注意到它使用的索引比使用GROUP BY的查询更有效