简体   繁体   中英

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).

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. when the next person will report this image as pornography I want the counter to be 101 and so on.

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

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

Use 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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