当您需要查询结果作为参数时,如何在SQL中加入?

时间:2014-07-25 01:05:14

标签: php mysql join

我正在进行查询,然后在while循环中运行另一个查询,我知道这是不好的做法。我知道我需要进行某种类型的连接,但是我需要将内部查询的结果作为外部查询的一部分,我不知道该怎么做。

$departments = $db->prepare("SELECT * FROM departments");
$departments->execute();

while ($row = $departments->fetch(PDO::FETCH_ASSOC))
{
    $department_id = $row['department_id'];

    $total_problems = $db->prepare("SELECT  COUNT(*) FROM `problems` WHERE department =$department_id"); 
    $total_problems->execute();
    $department_problems = $total_problems->fetchColumn(0);
}

我尝试了各种连接,但我无法正确理解它。

3 个答案:

答案 0 :(得分:2)

您正在寻找group by查询和left outer join

SELECT d.department_id, count(p.department_id)
FROM departments d left outer join
     problems p
     on d.department_id = p.department_id
GROUP BY d.department_id;

left outer join非常重要,因此您可以获得所有部门,无论他们是否有问题。

答案 1 :(得分:1)

围绕“问题”的反对可能是你的问题。

尝试改为:

    SELECT COUNT(*) FROM problems WHERE department = $department_id

编辑:

如果没有表格描述,很难给你一些工作代码,但试试吧。给出两个相关表:

departments
-----------
department_id
department_name

problems
--------
problem_id
department_id
problem_name

以下是您加入他们的方式,并且只按部门获取问题,而不会对问题进行任何描述:

SELECT d.department_name, COUNT(p.problem_id)
FROM departments AS d, problems AS p
WHERE p.department_id = d.department_id
GROUP BY d.department_name

那是在where子句中使用“旧样式”连接语法。

如果要显式使用JOIN子句,请尝试此操作(注意它未经测试,您的特定数据库可能不喜欢该连接语法):

SELECT d.department_name, COUNT(p.problem_id)
FROM departments AS d
INNER JOIN problems AS p ON d.department_id=p.department_id
GROUP BY d.department_name

答案 2 :(得分:0)

@Gordon已经解释了LEFT JOIN的重要性。在加入之前聚合problems可能会更快:

SELECT d.*, p.ct
FROM   departments d
LEFT   JOIN (
   SELECT department, count(*) AS ct
   FROM   problems
   GROUP  BY 1
   ) p ON p.department = d.department_id;

NULL返回ct,其中未发现任何问题 如果您想改为COALESCE(p.ct, 0) AS ct,请使用0

如果有问题的部门感兴趣,请使用[INNER] JOIN仅返回这些行。也更快。

除此之外:如果它不是拼写错误,我建议在department_id表格中使用problems作为列名。