我可以有一个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`
但是我也希望每个组中的行数按查询计算在普通组中.
+----------+-------------------------------------------------+
| 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
现在派生表将为每个类型包含max(id)和count,并且通过连接它,它将过滤所有其他记录.