I have a table to store client's answers.I want to use one mysql query to insert or update this table.
My Table name : questionform_answer
and columns > ClientID QuestionID OptionID
Each client can only have one same question id.For example
ClientID QuestionID OptionID
1 1 1
1 2 5
2 1 3
I want to update OptionID if already exist ClientID and QuestionID.I don't want to use select query so taking so time.
I tried
ON KEY UPDATE
Replace Into
But I could not.
I use php so I tried first update query and if mysqli return fail insert row but it is also slow.
MY insert and update code :
Insert Into questionform_answer (ClientID,QuestionID,OptionID) values
('$ClientID','$soruid','$cevapid')
Update questionform_answer set OptionID='$cevapid' where
ClientID='$ClientID' and QuestionID='$soruid'
One way around this is to add a unique key over (ClientID, QuestionID) and use an INSERT ... ON DUPLICATE KEY UPDATE query:
ALTER TABLE table1
ADD UNIQUE INDEX (ClientID, QuestionID);
INSERT INTO table1
VALUES (1, 1, 4)
ON DUPLICATE KEY UPDATE
OptionID = VALUES(OptionID)
Demo on dbfiddle
First of all, you should use prepared statements to avoid SQL injections.
If you have a unique key on (ClientID,QuestionID), you can do INSERT INTO ... ON DUPLICATE KEY like this:
INSERT INTO questionform_answer (ClientID,QuestionID,OptionID)
values ('$ClientID','$soruid','$cevapid')
on duplicate key update OptionID='$cevapid'
Related
I want to insert a row into my database table if the value of the first column does not exist in the table.
Example:
Name Value1 Value2
------------------------
John 2 3
Max 4 6
Alex 0 0
Now I want to insert a new person with the values 0 and 0 but only if the person does not exist. For example if I tried to insert John it would not do anything. All of this should happen in one single query.
Can anyone help?
Regards, Max
You can create a unique index on table(name) and then use insert ignore or insert on duplicate key update:
create unique index unq_t_name on t(name);
insert into t(name, value1, value2)
values ($Name, $value1, $value2)
on duplicate key update name = values(name);
The on duplicate key is a non-operation -- it does nothing if the name is already in the database.
Create an index on Name, make it unique. Thereafter you will not be able to add records where the name is already in there.
I have a MYSQL table that looks as follows:
id id_jugador id_partido team1 team2
1 2 1 5 2
2 2 2 1 1
3 1 2 0 0
I need to create a query to either INSERT new rows in the table or UPDATE the table. The condition is based on id_jugador and id_partido, meaning that if I wanted to insert id_jugador = 2 and id_partido = 1, then it should just UPDATE the existing row with the new team1 and team2 values I am sending. And dont duplicate the row.
However, if I have an entry id_jugador=2 and id_partido=3, since this combination does not exist yet, it should add the new row.
I read about the REPLACE INTO but it seems to be unable to check combination of UNIQUE KEYS.
If you have a UNIQUE KEY defined on the two columns (id_jugador, id_partido), then you can use:
INSERT ... ON DUPLICATE KEY ...
e.g.
INSERT INTO mytable (id_jugador, id_partido, team1, team2)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY
UPDATE team1 = VALUES(team1)
, team2 = VALUES(team2)
(Obviously, I'm assuming id is an AUTO_INCREMENT PRIMARY KEY, or there's a BEFORE INSERT trigger that generates a value for id when it's not provided.)
MySQL will attempt the INSERT (using up an auto_increment id value). If the INSERT succeeds, MySQL is done, it's just a regular insert. But if the INSERT throws a DUPLICATE KEY exception, then MySQL will perform an update action, equivalent to:
UPDATE mytable SET team1 = ?, team2 = ? WHERE id_jugador = ? AND id_partido = ?
Note that there can be multiple UNIQUE KEY constraints defined on a table. For the predicates of the UPDATE action, MySQL will use the columns/values of whichever unique (or primary) key is identified in the DUPLICATE KEY exception.
Also note that MySQL does actually attempt the INSERT, so MySQL does use up an AUTO_INCREMENT value, even when the INSERT throws a DUPLICATE KEY exception.
I normally avoid a REPLACE, because I usually have a lot of foreign keys, and I don't want a DELETE action. The DELETE action performed by REPLACE is a "real" DELETE; if there are foreign key references, the DELETE rule associated with the foreign key will be obeyed... the delete will fail if the DELETE rule is RESTRICT or NO ACTION and referencing rows exist, or if the DELETE rule is CASCADE or SET NULL, the referencing rows will be deleted or updated. I also believe any BEFORE/AFTER DELETE triggers will also be fired.
Apart from those options, you'd have to run two separate statements.
When I've needed to avoid an INSERT without having a UNIQUE KEY defined, I will typically do something like:
INSERT INTO mytable (id_jugador, id_partido, team1, team2)
SELECT i.*
FROM (SELECT ? AS id_jugador, ? AS id_partido, ? AS team1, ? AS team2) i
LEFT
JOIN mytable s
ON s.id_jugador <=> i.id_jugador
AND s.id_partido <=> i.id_partido
WHERE s.id IS NOT NULL
After the statement executes, test the number of affected rows. If it's zero, we know that the row was not inserted, so we can proceed with an UPDATE.
Structure table:
id (int primary key)
name (varchar 100)
date(datetime)
For insert I use query:
INSERT INTO table (name, date) VALUES ('t1','$date');
For delete row I use query:
DELETE FROM table WHERE name = 't1';
I would like want how make 1 query: first insert, if row with it name already exist, than delete row, and insert again.
Tell me please how to make it?
Create a UNIQUE index over your name column:
ALTER TABLE `table` ADD UNIQUE (name);
If you genuinely want to "delete row and insert again", then you can use REPLACE instead of INSERT. As documented:
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
Therefore, in your case:
REPLACE INTO `table` (name, date) VALUES ('t1','$date');
However, if instead of deleting the existing record and then inserting a new one you merely want to update the existing record, you can use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO `table` (name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE date = VALUES(date);
The most material difference is in the treatment of columns for which you do not provide explicit values (such as id in your example): REPLACE will result in the new record having the default value, whereas INSERT ... ON DUPLICATE KEY UPDATE will result in the old value being retained.
What you want to do is use MySQL's on duplicate update feature.
Can be used like this :
INSERT INTO table (name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE name=VALUES(name),dateVALUES(date);
Of course for that to happen a dupliate violation must occur.
insert into table (name, date) values('t1','$date') on duplicate key update name=values(name), date=values(date)
Are you looking for an update query?
Update will set a value on an already existing row.
UPDATE table SET date = '$newdate' WHERE name = 't1';
The best way to do this is using the mysql methods together with your query.
If you make the 'name' field unique:
id (int primary key)
name (varchar 100) NOT NULL UNIQUE
date(datetime)
And alter the query to:
INSERT INTO table
(name, date) VALUES ('t1','$date')
ON DUPLICATE KEY UPDATE date = "$date"
I have a frontend PHP application which will save data in a MySQL database. The updated_by value will change since it will be the user who is updating the record.
I would like to update the updated_by column ONLY when we are inserting new values for any of the other columns (sname, scol2) , and the record is inserted or updated.Any help is welcome, thank you so much :)
Table Info:
Table: test
Unique Index: columns sname and scol2
Columns: sname, scol2, updated_at, updated_by
Values: name1, col2, 03-02-2013, phpuser1
MySQL 5.6 Info:
INSERT INTO.. ON DUPLICATE KEY UPDATE: "..returns 1 if the row is inserted as a new row, and 2 if an existing row is updated..."
Example: users will Update or Insert records:
INSERT INTO test(sname) VALUES("name1") ON DUPLICATE KEY UPDATE sname="name1", scol2="col2";
Result: The above query will not update anything. Perfect.
INSERT INTO test(sname) VALUES("name1") ON DUPLICATE KEY UPDATE sname="name1", scol2="col22";
Result: The above query would update the columns: scol2 and updated_at .Perfect.
How to automatically update the updated_by column in one query?
INSERT INTO test(sname) VALUES("test1") ON DUPLICATE KEY UPDATE sname="name1", scol2="col2", updated_by="phpuser2222";
This wont work, it will update everytime the columns updated_by and updated_at
Possible solution with two queries:
Insert the record with: INSERT ... ON DUPLICATE KEY UPDATE...
Get the return value in my PHP application to know if it has been [updated or inserted], and then update the field updated_by with a second query: INSERT INTO test(updated_by) VALUES("phpuser2222");
Alright, i have revised the question to also include what i have so far, and what i want to do. So here goes it:
CREATE ORDER (
product_nat_id int(3) NOT NULL,
name VARCHAR(20),
PRIMARY KEY (product_nate_id)
)
INSERT INTO ORDER(product_nat_id, name) VALUES(1, 'Product 1');
INSERT INTO ORDER(product_nat_id, name) VALUES(2, 'Product 2');
INSERT INTO ORDER(product_nat_id, name) VALUES(3, 'Product 3');
CREATE TABLE INT_PRODUCT (
product_id INTEGER NOT NULL AUTO_INCREMENT,
product_nat_id INTEGER NOT NULL,
title TINYTEXT,
dateCreate TIMESTAMP CURRENT_TIMESTAMP,
CONSTRAINT INT_PRODUCT_PK PRIMARY KEY (product_id),
UNIQUE INT_PRODUCT_NK (product_nat_id));
But what i want is, whenever a record arrives with an updated value but duplicate key, i need to insert it (and not updated), but avoid duplicate constraint based on the difference in time inserted. Hope this makes sense now.
I would suggest the following:
Look up the previous record. I assume you should know what that would be
SELECT Count(*) FROM dim WHERE recordId = '$recordid'
If in step 1 the records returned are larger than 0 then invalidate the 'previous' record:
UPDATE dim SET datevalid = '$datevalue' where recordId = '$recordid' and status = 2
Continuing with step 1 where the ecords return in the check are larger than 0 now do the insert:
INSERT INTO dim (recordId,field1,field2,date,status) VALUES (1,'sad','123123','2013-03-26',1)
If step 1 was false then just do the insert:
INSERT INTO dim (recordId,field1,field2,date,status) VALUES (1,'sad','123123','2013-03-26',1)
I would add a status field just as an extra measure when you need to find records and distinguish between valid or invalid then you do not need to filter between dates. You can then use the status field. Also have a unique auto-increment key for every record even though the data might be the same for a set of valid and invalid records. recordId and unique key will not be the same in this case. You assign the recordId and the system will assign the unique key on the table. status = 1 is valid and status = 2 is invalid.
Hope this helps!
sample code of your post like as:
Insert query syntax looks like this:
INSERT INTO table (primarykeycol,col1,col2)
VALUES (1,2,3) ON DUPLICATE KEY UPDATE col1=0, col2=col2+1
If there is already a row with primarykeycol set to 1 this query is equal to:
UPDATE table SET col1=0, col2=col2+1 WHERE primarykeycol = 1
explanation as:
Ordinarily to achieve the same result you would have to issue an
UPDATE query, then check if there were affected rows and if not
issue an INSERT query.
This way, you can do everything in one step – first try insert and
then update if insert fails.
One situation for which this type of syntax is perfect is when you
work with daily counters. For example, you might have a table with
PostID, Date and Count columns.
Each day you’d have to check if you already created an entry for
that day and if so increase the count column – and this can be
easily substituted with one INSERT … ON DUPLICATE KEY UPDATE query.
Unfortunately there are some caveats. One being that when you have
multiple unique indexes it will act as if you had an OR condition in
WHERE clause of UPDATE query.
This means that multiple rows should be update, but INSERT … ON
DUPLICATE KEY UPDATE will update only one row.
MySQL manual: INSERT ON DUPLICATE KEY UPDATE Syntax