简体   繁体   English

SQL同时选择和计数

[英]SQL select and count at the same time

I am trying to select all from stuff and count the total amount of items in morestuff where stuff id = morestuff id. 我试图从东西中选择所有东西并计算更多东西中物品的总量,其中东西id = morestuff id。

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

Obviously there is something wrong with my query, can anyone help? 显然我的查询有问题,有人可以帮忙吗?

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}' 

This may be another option: 这可能是另一种选择:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM