I've this table skills here (id = auto increment & primary key):
| id | skill |
--------------
| 1 | PHP |
--------------
In this table I've the skill PHP. To insert a new skill I need to check if the skill already exists. I've tried it this way but it's not working. I'm not so familiar with MySQL / SQL:
Should not work:
INSERT INTO skills (`skill`) VALUES (`PHP`) ON DUPLICATE KEY UPDATE `skill` = `PHP`;
Should work:
INSERT INTO skills (`skill`) VALUES (`HTML`) ON DUPLICATE KEY UPDATE `skill` = `HTML`;
This is the right command:
INSERT INTO skills (`skill`)
VALUES ('PHP') -- fixed the backticks
ON DUPLICATE KEY UPDATE `skill` = 'PHP';
I assume the backticks are a typo. They should be single quotes.
Although I would write it as:
INSERT INTO skills (skill)
VALUES ('PHP')
ON DUPLICATE KEY UPDATE skill = VALUES(skill);
This will only "work" if you have a unique constraint on skill:
create unique index unq_skills_skill on skills(skill);
I would simply add an unique key on skills and use insert ignore
INSERT IGNORE INTO skills (`skill`) VALUES (`PHP`)
You can then use mysql_affected_rows() to verify whether any record added or not, if it returns 0 then no record added because of duplicate.
Related
I have the following table:
questions_answers
_____________________________________
| id | question_id | answer | user_id |
|____|_____________|________|_________|
| 1 | 1 | yes | 3 |
|____|_____________|________|_________|
I want to check if question_id and user_id exist, Then update the existing row.
I tried this command INSERT INTO questions_answers (question_id, answer, user_id) VALUES (1, 'no',3) ON DUPLICATE KEY UPDATE answer = 'no'
So in this case there is a question_id = 1 and user_id = 3, Hence it should update that row and not insert a new row.
But I think it checks the id column for dublicates.
Is there is a way to get this done with SQL or I need to check if row exists with PHP, then update?
Your INSERT INTO .. ON DUPLICATE KEY UPDATE is not working because the current KEY that determine the duplication/violation is the id column primary key.
From the spec of this syntax
INSERT ... ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE.
To achieve this, you will need to create a UNIQUE CONSTRAINT on two columns question_id and user_id. This unique constraint will raise upon the duplication of question_id - user_id pair, and triggers the UPDATE statement as you intends.
ALTER TABLE questions_answers ADD CONSTRAINT uq_user_question UNIQUE KEY(question_id ,user_id);
Reference:
MySQL Insert On Duplicate
MariaDB - INSERT ON DUPLICATE KEY UPDATE
What I have is a table of completed training. Each user has a username. Each user may completed numerous courses.
The table has the following headers:
+-------------------------+----------+---------+---------+---------+---------+-----------+
| recordnumber (KEY - AI) | username | type | course | status | started | completed |
+-------------------------+----------+---------+---------+---------+---------+-----------+
| int | varchar | varchar | varchar | varchar | date | date |
+-------------------------+----------+---------+---------+---------+---------+-----------+
And I have a PHP script set up to populate the db from a CSV upload.
What I'm trying to achieve is for it to add new rows, and to update existing ones.
The problem is that recordnumber (they key, unique field) is not constant. So instead of doing a "ON DUPLICATE KEY" query, I want to do it based on whether username and course already exist as a row.
Basically to say "If this username already has this course, update the other fields. If the username does not have this course, add this as a new row".
The query that I have at the moment (which works based on key) is:
INSERT into table(recordnumber, username,type,course,status,started,completed) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')
ON DUPLICATE KEY UPDATE username='$data[1]',type='$data[2]',course='$data[3]',status='$data[4]',started='$data[5]',completed='$data[6]'
Any thoughts on how I could amend the query to get it to check based on username and course instead of duplicate key?
Thank you. :-)
The most correct way would be to create a unique index on username - course columns and use on duplicate key update.
Obviously, you can issue a select before the insert checking for existing record with same user name and course and issue an insert or an update as appropriate.
create a key on the username and course column and then use on duplicate key
CREATE TABLE test (
username varchar(255) NOT NULL,
course varchar(255),
num_entries INT DEFAULT 0,
UNIQUE KEY (username, course)
);
insert into test (username, course) values
('billybob', 'math'),
('billy', 'math'),
('billybob', 'math'),
('bob', 'math')
ON DUPLICATE KEY UPDATE num_entries = num_entries + 1;
this is a simple example, but you should understand what to do from here
SAMPLE FIDDLE
so putting this to work on your table
ALTER TABLE `courses` -- assuming the table is named courses
ADD CONSTRAINT `UK_COURSE_USERNAME` UNIQUE (username, course);
then your insert should just be the same as what you have
Example query in reference to my comment above.
IF EXISTS(SELECT id FROM Table WHERE username = '$data[1]' AND course <> '$data[3]')
(
UPDATE username='$data[1]',type='$data[2]',course='$data[3]',status='$data[4]',started='$data[5]',completed='$data[6]'
)
(
INSERT into table(recordnumber, username,type,course,status,started,completed) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')
)
You might use ON DUPLICATE KEY UPDATE if you added unique constraint for username and course value pair like this:
ALTER TABLE `table` ADD CONSTRAINT `UK_table_username_course` UNIQUE (username, course);
I am trying to write a query to check if a record exists (based on couple of clause and not unique identifier) if such a search return records then I need to update all the found records if nothing found then I need to INSERT a record. Note that I can't use IF EXISTS because I am trying to make a query for a client side script and not a server side. So I came a cross the idea of INSERT INTO .... ON DUPLICATE KEY
Can I do this without knowing the row key identifier? So if I find a record where accountid = 17 and name = 'Mike' then update it to make the name 'Mike A' if there is no record with these 2 clause then insert a record.
This is an attempt that is giving me a syntax error
INSERT INTO test (name, accountid) VALUES ('Mike', 17)
ON DUPLICATE KEY
UPDATE test SET name='Mike A' WHERE name ='Mike' AND accountid = 17
Can this method handle what I am trying to do? If yes then can you please correct my syntax?
Thank you
The only way you can get this to work is if you have a primary key or unique constraint on the fields. From the documentation:
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. For example, if column a is
declared as UNIQUE and contains the value 1, the following two
statements have identical effect:
create table test (name varchar(100), accountid int);
insert into test values ('Mike', 17);
alter table test add unique (name, accountid);
insert int test (name, accountid) values ('Mike', 17)
on duplicate key update name='Mike A';
SQL Fiddle Demo
Without the unique key, it will insert a duplicate record.
already searched for such topics and found 2 different solutions but noone works.
My table has structure | ID (auto_increment primary_key) | UID (int) | FAV_ID (int) |
I need to insert new record to this FAV_TABLE if UID and FAV_ID (both) already exist.
Example of my query:
INSERT INTO FAV_TABLE (uid, fav_id) VALUES ($u_id,$s_id) ON DUPLICATE KEY UPDATE uid = uid
or this one
INSERT IGNORE FAV_TABLE (uid, fav_id) VALUES ($u_id,$s_id);
As mysql manuals says this query doesn't add record only if PRIMARY_KEY is the same.
And I need query not to add record if pair uid+fav_id is unique.
Any solutions? Thank you
You need to add a UNIQUE KEY on those columns:
ALTER TABLE FAV_TABLE ADD UNIQUE KEY(uid, fav_id);
INSERT IGNORE or ON DUPLICATE KEY works only when a unique key is duplicated.
You need to add a UNIQUE index on both fields uid and fav_id.
That way, when you insert a duplicate pair, it will be ignored.
I have a table:
CREATE TABLE Students (studentId TEXT PRIMARY KEY, name TEXT);
I want to insert records into the table, if I insert a student twice I want
the second insert to override(update) the first record.
INSERT INTO Students (StudentId, name) VALUES ('123', 'Jones');
INSERT INTO Students (StudentId, name) VALUES ('123', 'Jonas');
What's the best way of doing this?
Try REPLACE:
REPLACE INTO Students (StudentId, name) VALUES ('123', 'Jonas');
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.
You can also use the INSERT ... ON DUPLICATE KEY UPDATE syntax:
INSERT INTO Students
(StudentId, name)
VALUES ('123', 'Jones')
ON DUPLICATE KEY UPDATE
name = VALUES(name) ;
See this answer: insert-ignore-vs-insert-on-duplicate-key-update for differences between REPLACE, INSERT ... ON DUPLICATE KEY UPDATE and INSERT IGNORE.
But please, tell us that the studentId TEXT PRIMARY KEY is a typo. Do you really have a Primary Key that is TEXT datatype? The name (studentId) suggests that it could be a simple INT or INT AUTO_INCREMENT.
If you are using MySql - just use REPLACE instead of INSERT
I had a similar issue, but with a table that already had data in it, and no foreign keys, so my solution was very simple:
I added a new column called temp_id and made that a primary key, then afterwards deleted the old ID column, and then renamed the temp_id column to id.