除最新记录外,组行计数

时间:2016-06-05 11:15:43

标签: mysql

我可以使用group by子句以该查询运行方式返回每个组的最新记录:

select `id`, `user_id`, `type`, `product_id`
    from `table` where `id` in 
        (select max(`id`) from `table` where `product_id`=1 group by `type`)
order by `id` group by `type`

但我也希望每个组中的行数在普通group by查询中计算。

+----------+-------------------------------------------------+
|   type   | select count(1) where type=:type group by type; |
+----------+-------------------------------------------------+
|   one    |                        5                        |
+----------+-------------------------------------------------+
|   two    |                        1                        |
+----------+-------------------------------------------------+
|   three  |                        109                      |
+----------+-------------------------------------------------+

是否也可以拥有这些数字?

1 个答案:

答案 0 :(得分:2)

您可以使用JOIN

执行此操作
SELECT t.id,t.user_id,t.type,t.product_id,s.cnt
FROM YourTable t
INNER JOIN (SELECT p.type,max(p.id) as max_id,count(*) as cnt
            FROM YourTable p
            WHERE p.product_id = 1
            GROUP BY p.type) s
 ON(t.id = s.max_id)
WHERE t.product_id = 1

现在,派生表s将包含每个type max(id)count,并且通过加入它,它将过滤所有其他记录。< / p>