-2

enter image description here

How can I write the query, select albums.*, count number of images in images table, if no images on albums count as zero. One album may has 0 or more images.

The following query result in no rows when the album has no images.

SELECT `albums`.*, count(images.id) as num 
FROM (`albums`) 
INNER JOIN `images` ON `images`.`album_id`=`albums`.`id`
1
  • Use a left join instead of an inner join.
    – crthompson
    Oct 7, 2014 at 17:11

1 Answer 1

1

Try this... You need to use a left join and a group by

  SELECT `albums`.*, count(images.id) as num 
  FROM (`albums`) 
  LEFT JOIN `images` ON `images`.`album_id`=`albums`.`id`
  GROUP BY albums.id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.