mysql - 除最新记录外的组行数

标签 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                      |
+----------+-------------------------------------------------+

是否也可以有这些数字?

最佳答案

您可以使用 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 将包含每个 typemax(id)count ,通过加入它,它将过滤所有其他记录。

关于mysql - 除最新记录外的组行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37641203/

相关文章:

sql - MySQL 错误 : ON DUPLICATE KEY UPDATE, 列计数与行的值计数不匹配

php - 使用 PHP 在 while 循环中显示单个列

php - 如何制作受控的 "shuffle"订单?

MySQL 左外连接查询

php - MySql - 从中​​选择 - 不要显示重复的单词 - 也许是 "on duplicate key"?

Mysql 使用 Cron 作业导出和发送邮件

mysql - 选择值子组

mysql - 如何将 sql 时间戳作为列名?

php - SQL/PHP 如何验证日期是否在日期范围之间?

php - 使用带有单词边界的 MySQL 和 REGEX 的 Codeigniter Query Builder 增加了额外的空间