简体   繁体   English

自动增量作为SQL中的计数器

[英]Auto-increment as a counter in SQL

I have a table with 3 columns (imageId, reportId, counter) the primary key of the table is the columns (imageId, reportId) now I want the counter columns will be the counter of how many times i've tried to insert the pair (imageId, reportId). 我有一个包含3列(imageId,reportId,counter)的表,该表的主键是列(imageId,reportId),现在我希望计数器列将是我尝试插入该对的次数的计数器(imageId,reportId)。

for example if i have the image "x.png" and 100 people reported that this image contains pornography, i want that the row in the table with the value ("x.png", "pornography") will have 100 in the counter column. 例如,如果我有图像“ x.png”并且有100个人报告该图像包含色情内容,我希望表格中具有值(“ x.png”,“色情”)的行的计数器为100柱。 when the next person will report this image as pornography I want the counter to be 101 and so on. 当下一个人将该图片报告为色情内容时,我希望计数器为101,依此类推。

how can i do such thing? 我该怎么做?

thank you 谢谢

In this scenario it would be best to add new rows to your table. 在这种情况下,最好将新行添加到表中。 This means you can provide a view over the top of this which can select the counts as you require. 这意味着您可以在其顶部提供一个视图,可以根据需要选择计数。

The benefit of a new row per report is the ability to also allow users to add custom messages etc. 每个报表新行的好处是还可以允许用户添加自定义消息等。

-- Update -更新

Some details here on views here http://dev.mysql.com/doc/refman/5.0/en/view-syntax.html 有关视图的一些详细信息,请参见http://dev.mysql.com/doc/refman/5.0/en/view-syntax.html

At the heart of it your query will just be a basic query like 从本质上讲,您的查询将只是一个基本查询,例如

SELECT imageId, reportId, count(reportId) as count FROM training.reporttable group by imageId, reportId

Here is a basic example: 这是一个基本示例:

选择字段数

Note, I stuck with your example data but reportId and imageId should be normalised 注意,我坚持使用您的示例数据,但是reportId和imageId应该规范化

Use INSERT ... ON DUPLICATE KEY UPDATE 使用INSERT ... ON DUPLICATE KEY UPDATE

INSERT IGNORE INTO table (imageId, reportId, counter) VALUES (1, 1, 0) ON DUPLICATE KEY UPDATE SET counter=counter+1

You could also set the default value of the counter column to 0 and use this: 您也可以将counter列的默认值设置为0并使用此值:

INSERT IGNORE INTO table (imageId, reportId) VALUES (1, 1) ON DUPLICATE KEY UPDATE SET counter=counter+1

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

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