dpx86402 2014-03-28 15:10
浏览 117
已采纳

mysql join:为每种类型获取包含count的部分

I have two tables:

1) parts

part_id  |  part_name

2) posts

post_id | part_id | type | title | content

in posts table the post has one of three types, so in type column I put value (1 or 2 or 3)

I want to get table (with count and join) like this

part_id | part_name | count_posts_type1 | count_posts_type2 | count_posts_type3

how to do this with mysql?

example:

enter image description here

  • 写回答

2条回答 默认 最新

  • douba9654 2014-03-28 15:27
    关注

    using sum with case when is a rather common way to do this if you have a limited list of types.

    Then a left join to have result for parts without post (and a coalesce to have 0 instead of null on sums), and here we go.

    select 
    pa.part_id, pa.part_name,
    coalesce(sum(case when po.type = 1 then 1 else 0 end), 0) as count_posts_type1,
    coalesce(sum(case when po.type = 2 then 1 else 0 end), 0) as count_posts_type2,
    coalesce(sum(case when po.type = 3 then 1 else 0 end), 0) as count_posts_type3
    from parts pa
    left join posts po on po.part_id = pa.part_id
    group by pa.part_id, pa.part_name
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址