Majinbibo
Majinbibo

Reputation: 159

Mysql Conditional Count

I have this assets table:

asset_id      | mediumint(8)
asset_type_id | mediumint(8)
asset_name    | varchar(200)

and a lookup table:

product_id | mediumint(8)
asset_id   | mediumint(8)
sequence   | smallint(3)

Basically, the lookup table can have multiple entries of assets for an item. And you can get the item description in assets table.

The assets is categorized as an image, video, sound, etc based on its asset_type_id. This asset_type_id is comprises of integers 1 to 16.

Now, I want to count the number of images(1), video(2) and sound(3) ONLY for a particular item. Is there anyway I can do this using one SELECT QUERY?

I can't limit my selection to just asset_type_id = 1 or 2 or 3 because I still need the other assets data.

Upvotes: 0

Views: 966

Answers (1)

gbn
gbn

Reputation: 432210

SELECT 
   l.product_id, t.asset_type_id, COUNT(*)
FROM
   lookup l
   CROSS JOIN
   (SELECT 1 AS asset_type_id UNION ALL SELECT 2 UNION ALL SELECT 3) t
   LEFT JOIN
   assets a ON l.asset_id = a.asset_id AND t.asset_type_id = a.asset_type_id
GROUP BY
   l.product_id, t.asset_type_id;

Edit: as separate columns

SELECT 
   l.product_id, 
   COUNT(CASE WHEN a.asset_type_id = 1 THEN 1 END) AS asset_count_image,
   COUNT(CASE WHEN a.asset_type_id = 2 THEN 1 END) AS asset_count_video,
   COUNT(CASE WHEN a.asset_type_id = 3 THEN 1 END) AS asset_count_sound
FROM
   lookup l
   LEFT JOIN
   assets a1 ON l.asset_id = a.asset_id AND a.asset_type_id IN (1, 2, 3)
GROUP BY
   l.product_id;

Upvotes: 5

Related Questions