我可以有一个 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 |
+----------+-------------------------------------------------+
是否也可以有这些数字?
最佳答案
您可以使用 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
,通过加入它,它将过滤所有其他记录。
关于mysql - 除最新记录外的组行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37641203/