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.
Related
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'
I have a following map table, with a unique key on the name column:
id | name
1 aaa
2 bbb
3 ccc
I want to get a newly created ID if I insert a new value to this table, like this:
INSERT IGNORE INTO map VALUES(null, 'ddd');
I know I can do this with getLastId() function. But I also want to get ID if a name already exists, and getLastId() function returns 0 in such case:
INSERT IGNORE INTO map VALUES(null, 'ccc');
Is this possible to do with one SQL, and without checking if a record exists, etc?
I think you need to go the extra mile for that one:
check if exists - when so: get ID of that name
if not: SELECT LAST_INSERT_ID();
Depends on what qualifies as a single query.
When you make use of INSERT INTO ... ON DUPLICATE KEY UPDATE you can control the LAST_INSERT_ID() in such a manner that it will return the new id on insert and the id of the row "updated" on update:
INSERT INTO map (name) VALUE ('ccc')
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id);
That will make the LAST_INSERT_ID() then return the map.id of the row you're interested in.
Whatever the API is that you name as the getLastId() (I don't know it so I can't provide more pointers on it) this may not work and you would then need to fire a second query to obtain it:
SELECT LAST_INSERT_ID();
See as well:
MySQL ON DUPLICATE KEY - last insert id? (Stackoverflow Q&A, Apr 2009)
table1 : bo_indexable_attribute
id version mcs name search_id
285 3 13 name1 16
286 3 13 name2 16
287 3 13 name3 16
what i want is copying the content of this table and insert it into it again but this time with different mcs column
so my tryings is
CREATE TEMPORARY TABLE bo_scenario_indexable_attribute_temp (SELECT * FROM bo_scenario_indexable_attribute WHERE mcs = #sales );
UPDATE bo_scenario_indexable_attribute_temp SET mcs = #sales_master;
INSERT INTO bo_scenario_indexable_attribute SELECT * FROM bo_scenario_indexable_attribute_temp;
but this gives me Duplicate entry '285' for key 'PRIMARY'
any suggestions ??
You have copied your table into temporary one by the first statement. Then by the second you do an update and in the third statament you are trying to insert into the first table the same records. Maybe your id column has unique key so you get a "duplicate entry for key primary".
Take a look here: SQL UNIQUE Constraint
As #Franky pointed out, your id column has a unique constraint. Use this:
INSERT INTO bo_scenario_indexable_attribute SELECT version, mcs, name, search_id FROM bo_scenario_indexable_attribute_temp;
By leaving the id value out of insertion it the column will be assigned a new, unused id value which satisfies the unique constraint placed upon the column.
Edit based on first comment:
Use below queries:
CREATE TEMPORARY TABLE bo_scenario_indexable_attribute_temp (SELECT version, mcs, name, search_id FROM bo_scenario_indexable_attribute WHERE mcs = #sales );
UPDATE bo_scenario_indexable_attribute_temp SET mcs = #sales_master;
INSERT INTO bo_scenario_indexable_attribute SELECT version, mcs, name, search_id FROM bo_scenario_indexable_attribute_temp;
You got that error because you fetched more columns in your SELECT than you are inserting in your INSERT.
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"
Is there a way to set the value of another column to primary key (auto increment)?
Basically what I am trying to achieve is this
ID Stuff
---- ------
1 1
2 324
3 64
4 94
5 ...
Now when I am adding the the fifth row with a query like
INSERT into TABLE values(NULL, NULL);
So when the second value is NULL I want it to be equal to ID.
I tried INSERT triggers but it doesnt work. Any ideas?
I don't think you can do that in one step, but you can first insert and then update...
One possibility is to expose a stored procedure, and when the Stuff parameter is null, update the insert with the LAST_INSERT_ID(), otherwise pass the non-null value to the insert.
Try this:
INSERT INTO `TABLE` (`ID`,`Stuff`) VALUES(NULL, `ID`);