3

我正在尝试从 stuff 中选择所有内容并计算 morestuff 中的项目总数,其中 stuff id = morestuff id。

select *,
    COUNT(morestuff.items) as total
from stuff,
    morestuff
where stuff.id = '{$id}'
    and morestuff.id = stuff.id

显然我的查询有问题,有人可以帮忙吗?

4

2 回答 2

3
SELECT s.*, coalesce(ms.Count, 0) as Count
FROM stuff s
left outer join (
    select id, count(*) as Count
    from morestuff
    group by id
) ms on s.id = ms.id
WHERE s.id='{$id}' 
于 2012-05-17T18:52:49.620 回答
2

这可能是另一种选择:

select
  *, (
    select count(*)
    from morestuff
    where morestuff.id = stuff.id
      ) as total
from stuff
where id = '{$id}'
于 2012-05-17T19:37:34.670 回答