Skip to content
Advertisement

Mysql : Get COUNT(B.column) as B_count and Left Join B where B_count not equals to 0

I am trying to get rows where the count column b_count is not 0

SELECT `tags`.*, 
       Count(`album_picture_tag`.`tag_id`) AS `c_count` 
FROM   `tags` 
       INNER JOIN `album_picture_tag` 
               ON `tags`.`id` = `album_picture_tag`.`tag_id` 
WHERE  `tags`.`id` = 16 
       AND `c_count` != 0; 

but it keeps giving me the error: #1054 - Unknown column 'c_count' in 'where clause'

which part am I missing?

Advertisement

Answer

you need to use having clause with group by and use expression instead of alias name

SELECT `tags`.id, 
       Count(`album_picture_tag`.`tag_id`) AS `c_count` 
FROM   `tags` 
       INNER JOIN `album_picture_tag` 
               ON `tags`.`id` = `album_picture_tag`.`tag_id` 
WHERE  `tags`.`id` = 16 
group by `tags`.id
having Count(`album_picture_tag`.`tag_id`) != 0
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement