SQL selection and calculation at the same time

I am trying to select everything from the material and count the total number of elements in morestuff, where 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 request, can anyone help?

+3
source share
2 answers

This may be another option:

select
  *, (
    select count(*)
    from morestuff
    where morestuff.id = stuff.id
      ) as total
from stuff
where id = '{$id}'
+3
source
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}' 
+3
source

All Articles