我可以使用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 |
+----------+-------------------------------------------------+
是否也可以拥有这些数字?
答案 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>