php - Combination of 2 sql tables -


i have following tables (its simplified) :

 customers  -int id  -varchar name   envents  -int id  -int customer_id  -int duration 

my problem , want sum of durations same customer_id , replace customer_id name table customers.

so output should :

 +--------------+----------------+ | name         | sum(durtaions) | +--------------+----------------+ | customername |          12313 | +--------------+----------------+ 
  • thats example.

can give me hint?

try join both tables , use group by clause achieve this:

select c.name       ,sum(e.duration) duration   customers c    join events e      on c.id = e.customer_id  group c.id 

see this sample sqlfiddle


edit:

try left join customers name duration 0 if not in events table

select c.name       ,ifnull(sum(e.duration),0) duration   customers c    left join events e      on c.id = e.customer_id  group c.id 

see this sqlfiddle

have @ joins in mysql , a visual explanation of sql joins


Comments