SQL查询工作而不工作

时间:2014-09-20 08:40:13

标签: sql join where

我已经问过一些问题来进行此查询,但仍然无法正常工作: 如果我使用这个SQL代码,它可以工作:

SELECT
   l.inlog AS inlog,
   u.naam AS naam,
   SUM(o.status='afgewerkt') AS oefn
FROM 
   users AS u
LEFT JOIN     
   llntoets AS l ON (u.inlog = l.inlog)
LEFT JOIN     
   oefeningen AS o ON (u.inlog = o.speler AND o.btijd between '$bdatum' AND '$edatum')
WHERE
   code = '$code'
GROUP BY 
   l.inlog

如果我使用此代码:

SELECT
   l.inlog AS inlog,
   u.naam AS naam,
   SUM(o.status='afgewerkt') AS oefn,
   SUM(b.status='afgewerkt') AS begripn
FROM 
   users AS u
LEFT JOIN     
   llntoets AS l ON (u.inlog = l.inlog)
LEFT JOIN     
   oefeningen AS o ON (u.inlog = o.speler AND o.btijd between '$bdatum' AND '$edatum')
LEFT JOIN     
   begrippen AS b ON (u.inlog = b.speler AND b.btijd between '$bdatum' AND '$edatum')
WHERE
   code = '$code'
GROUP BY 
   l.inlog

即使在begrippen和oefeningen这两个表具有完全相同的结构,如果我输入第一个代码,oefn显示它应该是完美的数字,如果我采用第二个代码它会使数字完全错误。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

当您加入一个表中有多个记录匹配您加入的每个记录时,这将导致其他联接的记录重复。

您可以使用子查询来计算其他表中的记录:

select
  l.inlog AS inlog,
  u.naam AS naam,
  (
    select count(*)
    from oefeningen
    where
      speler = u.inlog and
      btijd between '$bdatum' and '$edatum' and
      status = 'afgewerkt'
  ) as oefn,
  (
    select count(*)
    from begrippen
    where
      speler = u.inlog and
      btijd between '$bdatum' and '$edatum' and
      status = 'afgewerkt'
  ) as begripn
from
  users as u
  left join llntoets as l on (u.inlog = l.inlog)
where
  code = '$code'
group by
  l.inlog