简体   繁体   English

MySQL:按类别计算项目

[英]MySQL: Count items by categories

I've created a table that holds items according to categories: 我创建了一个表,根据类别保存项目:

+------------+---------------------+------+-----+-------------------+----------------+
| Field      | Type                | Null | Key | Default           | Extra          |
+------------+---------------------+------+-----+-------------------+----------------+
| id         | bigint(20) unsigned | NO   | PRI | NULL              | auto_increment |
| name       | varchar(30)         | YES  |     | NULL              |                |
| category   | varchar(30)         | YES  | MUL | NULL              |                |
| timestamp  | timestamp           | NO   |     | CURRENT_TIMESTAMP |                |
| data       | mediumblob          | YES  |     | NULL              |                |
+------------+---------------------+------+-----+-------------------+----------------+

Old data is deleted using a sliding window technique , meaning that only the last N items in each category are kept in the table. 使用滑动窗口技术删除旧数据,这意味着每个类别中只有最后N项目保留在表格中。

How can I keep track the total number of the items per category, and the timestamp of the first item in the category? 如何跟踪每个类别的项目总数以及该类别中第一个项目的时间戳?

Edit - COUNT and MIN on the original table won't work, because this is a Sliding Window data structure meaning that the first items have already been deleted. 编辑 - 原始表上的COUNTMIN将不起作用,因为这是一个滑动窗口数据结构,意味着第一个项目已被删除。

Clearly you need to keep a separate table when you delete the records. 显然,删除记录时需要保留一个单独的表。 Your table should summarize the categories and include the fields: 您的表应该总结类别并包括以下字段:

  • Category first start time 类别第一个开始时间
  • Total number of items in the category 该类别中的项目总数

and so on. 等等。

When you go to delete, you need to update this table. 当您要删除时,您需要更新此表。 In general, I prefer to use stored procedures to handle database maintenance, so this code could be added to the stored procedure. 通常,我更喜欢使用存储过程来处理数据库维护,因此可以将此代码添加到存储过程中。 Others prefer triggers, so you could have a delete trigger that does the same thing. 其他人更喜欢触发器,因此您可以使用删除触发器执行相同的操作。

尝试使用SELECT count(id) FROM table GROUP BY category

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM