Mysql Conditional Count

后端 未结 1 459
甜味超标
甜味超标 2021-01-28 02:55

I have this assets table:

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

1条回答
  •  礼貌的吻别
    2021-01-28 03:43

    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;
    

    0 讨论(0)
提交回复
热议问题