【问题标题】:mysql join: get parts with count for each typemysql join:获取每种类型的计数部分
【发布时间】:2014-03-28 15:10:44
【问题描述】:

我有两张桌子:

1) 零件

part_id  |  part_name

2) 帖子

post_id | part_id | type | title | content

在帖子表中,帖子具有三种类型之一,因此在类型列中我输入值(1 或 2 或 3)

我想得到这样的表(带有计数和连接)

part_id | part_name | count_posts_type1 | count_posts_type2 | count_posts_type3

如何用 mysql 做到这一点?

示例:

【问题讨论】:

  • 这两张表有什么共同点?
  • 常见的是 part_id 我修好了
  • 我为我需要的结果添加了一个示例

标签: php mysql join count


【解决方案1】:

如果类型列表有限,则使用 sum 和 case when 是一种相当常见的方法。

然后是左连接以获得没有帖子的部分的结果(并且合并以使总和为 0 而不是 null),然后我们开始。

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

【讨论】:

    【解决方案2】:

    你有没有尝试过类似的东西(只是开玩笑,我知道你什么都没试过)

    SELECT
         parts.part_id,
         parts.part_name,
         COUNT(t1.post_id) AS count_posts_type1,
         COUNT(t2.post_id) AS  count_posts_type2,
         COUNT(t3.post_id) AS count_posts_type3
    FROM posts
         RIGHT JOIN part ON posts.part_id=parts.part_id 
         INNER JOIN ( SELECT post_id FROM posts WHERE type=1 ) as t1(post_id) ON posts.post_id = t1.post_id
         INNER JOIN ( SELECT post_id FROM posts WHERE type=1 ) as t2(post_id) ON posts.post_id = t2.post_id
         INNER JOIN ( SELECT post_id FROM posts WHERE type=1 ) as t3(post_id) ON posts.post_id = t3.post_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多