I am building a rating system, and i want to insert a new row, if the name field does not already contain the name i want to insert, and if it does exist, i want to increase the count field by 1
For example, if i have a row the the name 'Tom' and i try to insert another row with the name 'Tom, then i want to +1 for the field count on the row that already exists.
If a row with the name 'Tom' does not exist, i want to insert a new one and set count to 1.
I know i could do this with about 3 SQL statements and some if statements, but that would slow down the script as 2/3 sql commands are being executed.
Any ideas?
Thanks!
see INSERT ... ON DUPLICATE KEY UPDATE
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.
e.g.
INSERT INTO table (name,counter) VALUES ('Bob', 1)
ON DUPLICATE KEY UPDATE counter=counter+1
Related
I want to insert if in the table is not same row with values, but if there is row with the same values I want to only update one that will add +1 to the current value. I have current code, but it doesn't seem to update values in row that exists.
INSERT INTO raport(id, wykonawca, tytul, czas_trwania, powtorzenia)
VALUES('','$wykonawca2','$tytul2','$czas_trwania2', '$powtorzenia2')
ON DUPLICATE KEY UPDATE wykonawca='$wykonawca2', tytul='$tytul2', czas_trwania='$czas_trwania2',
powtorzenia='$powtorzenia2'+1
Ensure your table has a column declared as UNIQUE or PRIMARY KEY and is not an Auto-increment column
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be inserted would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row occurs. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE t1 SET c=c+1 WHERE a=1;
(The effects are not identical for an InnoDB table where a is an auto-increment column. With an auto-increment column, an INSERT statement increases the auto-increment value but UPDATE does not.)
MySQL Reference
EDIT :
Your id column is empty you need to pass a value
The actual answer to your initial question as to why the rows do not update is because you are not passing a value for the PRIMARY KEY - this is your AUTO-INCREMENT id column.
Every time you pass :
VALUES('','$wykonawca2','$tytul2','$czas_trwania2', '$powtorzenia2')
this means that your id column is blank, so there is no duplicate just a new row. If you want to have an ON DUPLICATE KEY UPDATE you'll need to pass in the id.
For some more info about ways to handle multiple indexes and DUPLICATE UPDATE check this question out: MySQL behavior of ON DUPLICATE KEY UPDATE for multiple UNIQUE fields
Also, you should read this and action it as soon as possible, you shouldn't be passing variables straight into sql - it's hugely outdated and very unsafe:
How can prepared statements protect from SQL injection attacks?
Iam using a table in Mysql database and here there is a field called as First_Seen and Last_Seen and one of the field ID is marked as primary Key.
Now suppose my record is like this
12445555555|1|4444444855|2017-03-09 15:02:55|abc|134|M|SOME_RANDOM_NAME
Out of these 1244555555 field is made primary key.
SO if I try to insert this record into database it is inserting properly with both first_seen and last_seen as 2017-03-09 15:02:55.
But whenever the script executes the same command after 10 min (say) because the id is made primary key,the next record with different time like this is not inserted.
12445555555|1|4444444855|2017-03-09 15:12:55|abc|134|M|SOME_RANDOM_NAME
So all I wanted to do instead of inserting duplicate record into database I want to update the last_seen field.Any suggestions on this.Because even the script executes the same record n no of times it won't be reflected in database.
This is the db_insert.py script which takes the record from the csv file and extract the fields and insert into db
time = record[6]
try:
cursor = connection.cursor()
# Trying to create a new record
sql = "INSERT IGNORE INTO `my_table` (`ID`,`F1`,`F2`,`First_Seen`,`Last_Seen`,`F3`,`F4`,`F5`,`F6`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql,(id,f1,f2,time,time,f3,f4,f5,f6))
connection.commit()
finally:
connection.rollback()
connection.close()
All i wanted is whenever the duplicate entry occurs matching the id field then i need to replace the time with the time field in the current row and put it in last_seen.
This is what iam expecting.
12445555555|1|4444444855|2017-03-09 15:02:55|2017-03-09 15:12:55abc|134|M|SOME_RANDOM_NAME|something_else
Use ON DUPLICATE KEY UPDATE
INSERT INTO table (id, column1, column2)
VALUES(1, 'inserted value1', 'inserted value2') ON DUPLICATE KEY UPDATE column1="updated value 1", column2='updated value 2'
I have a mysql on duplicate key statement.
mysql_query("INSERT INTO statistics (classify, apply) VALUES ('$classify', 1)
ON DUPLICATE KEY UPDATE apply = apply + 1");
id classify apply
1 A 1
but it didn't update the existing row and it keep add another row, Where is the problem?
It's probably the column classify is not unique. You need to have a UNIQUE field in the table to make ON DUPLICATE KEY UPDATE work. If you have not set one, you can execute this statement below.
ALTER TABLE statistics ADD CONSTRAINT tb_uq UNIQUE (classify)
ON DUPLICATE KEY will update a row only when you try to insert a record that would throw a duplicate keys error (like the name states). So this happens only if you are a using a unique key or a primary key for that column. It looks like you didn't created a unique key for the classify column.
If I run an insert query but it fails because of duplicated key error is there any way to get its primary key without doing another select?
Basically:
INSERT INTO tbl (field) VALUES ('myvalue')
This fails because there is already a record with ID:1 and field:myvalue.
Now I Want to know that ID:1 without doing another query:
SELECT id FROM tbl WHERE field = 'myvalue'
is it possibile?
Here is a link that provides four different ways to deal with this:
http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/
There is a provision with each library to get the id of the row which is inserted.
Like: for simple mysql_query() use mysql_insert_id() after that to retrive the id of the last inserted row
Check this link
EDIT:
Please Check that if you have defined the unique index for field column.
If yes then you cannot insert duplicate in the column field
I have a mySQL query using ON DUPLICATE KEY UPDATE that I am runnining from a PHP script. I would like to test whether an UPDATE or an INSERT occurred. How can I do that?
From MySQL documentation:
"With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated."
You can use mysql_affected_rows() to determine the number of rows affected.
I had to figure this out one time, so I'm referring to my notes on the matter.
The following query:
INSERT INTO table ... ON DUPLICATE KEY UPDATE ..., id = LAST_INSERT_ID( id)
Where 'id' is the primary key on the table, allows you to call mysqli_affected_rows(), which will return:
0 - Row existed, nothing updated
1 - No row existed, inserted
2 - Row existed, something updated