I am trying to do a sql insert only if the data doesn't already exist in the table. I have a language table that has a auto incremented primary id field and a string description field to capture the name of the language(ex. English). I want to be able to insert into the database only if the description field is not already there. The primary id doesn't matter. So I only want to insert into the table if "English" isn't already a value in the table. Also, I am only given the description to check if it's already in the database (I mention this because the ON DUPLICATE KEY requires all fields to be matching and I don't have the id).
I have searched and tried so many queries without any of them producing the correct results. Any ideas would be helpful. Thanks.
You would simply add a UNIQUE constraint to the description field.
and then use "INSERT ... ON DUPLICATE KEY UPDATE" in your code. Refer this link.
if you need to update rows that have UNIQUE key conflict - you should use "meda" answer.
if you need only insert rows without duplicates you should also add UNIQUE constraint but with using query:
INSERT IGNORE INTO table SET ....
this query will insert row that have no conflict and ignore others without any mysql errors
Related
I have a table that looks like the following
Basically I want to check if the combination of (score_id, rater, rated) already exists in the database, if it does, then I update the score field, otherwise I insert a new record into the DB.
I tried INSERT ON DUPLICATE KEY UPDATE but it only works on the primary key. I'm looking for something similar but works on the values in other columns.
Solved it by creating a unique key on those three columns with alter table scores add unique key 'score_record' ('score_id', 'rater', 'rated');
The table already has duplicates entries. I want to create a unique constraint in MQSL DB without deleting the existing duplicates. If any duplicate entries coming onwards then it will show an error. Given blow queries not working in MYSQL.
ALTER TABLE presence
ADD CONSTRAINT present uniqueness UNIQUE (employee_id,roll_number) where id >10000;
or
ALTER TABLE presence
ADD CONSTRAINT present uniqueness UNIQUE (employee_id,roll_number) where id <> (343,34534,34534)
Do we have something like that solution in SQL?
Add an additional column to the table that indicates the existing values.
Set it to NULL for the existing values. And give it a constant value, say 1, for the new rows. Then create a unique index or constraint on this column:
alter table t add constraint unique (employee_id, is_old)
Actually, I realize that you probably don't want duplicates with singleton old values and new values. That is just an issue of setting the value to NULL only for duplicates in the history. So, one row would have a constant value (say 1) in the historical data.
MySQL allows duplicate values on NULL, which is why this works.
In my server I'm adding values to database using a command like
INSERT INTO votes VALUES ('1',0),('2',0),('3',0)
The primary key is the first argument of each value key. Sometimes, when adding, the primary key may already exist in the table.
The issue is that, if that happens, I get an error, and it stops the whole process of adding them all.
Is there a way such that, if the current key already exists, then it just skips the current value set, and moves on to the next one?
Thanks
INSERT IGNORE INTO votes VALUES ('1',0),('2',0),('3',0);
No need to explicitly assign primary key if the primary key is AUTO_INCREMENT.
Assuming your table votes has 2 columns: id and data:
The query is:
INSERT INTO votes (`data`) VALUES (0),(0),(0)
Yes, use INSERT IGNORE syntax, it will work
I've got a mysql database with a table that has both a auto-increment primary key and unique string valued key (a sha-1 hash).
If I try to add a record that has the same sha-1 hash as an existing record, I just want to get the primary key of the existing record. I can use something like "INSERT ... ON DUPLICATE KEY UPDATE" or "INSERT IGNORE" to prevent an exception when trying to insert a record with a existing hash value.
However, when that happens, I need to retrieve the primary key of the existing record. I can't find a way to do that with a single SQL statement. If it matters, my code is in Java and I'm using JDBC.
Alternatively, I can do it with two statements (either a query followed by an insertion if not found, or a insertion followed by a query if a duplicate key exists). But I presume a single statement would be more efficient.
If I try to add a record that has the same sha-1 hash as an existing
record, I just want to get the primary key of the existing record. I
can use something like "INSERT ... ON DUPLICATE KEY UPDATE" or "INSERT
IGNORE" to prevent an exception when trying to insert a record with a
existing hash value.
If you have an UNIQUE index on a column, no matter what you tried, the RDMS will not allow duplicates in that column (except for the NULL value).
As you said, there is solution to prevent "error" if this appends. Probably INSERT IGNORE in your case.
Anyway, INSERT and UPDATE modify the database. MySQL never return values for these statements. The only way to read your DB is to use a SELECT statement.
Here the "workaround" is simple, since you have an UNIQUE column:
INSERT IGNORE INTO tbl (pk, sha_key) VALUES ( ... ), ( ... );
SELECT pk, sha_key FROM tbl WHERE sha_key IN ( ... );
-- ^^^
-- Here the list of the sha1 keys you *tried* to insert
Actually, INSERT...ON DUPLICATE KEY UPDATE is exactly the right statement to use in your situation. When you use ON DUPLICATE, if the insert happens without duplicate, JDBC returns count of 1 and the ID of the newly inserted row. If the action taken is an update due to duplicate, JDBC returns count of 2 and both the ID of the original row AND the newly generated ID, even though the new ID is never actually inserted into the table.
You can get the correct key by calling PreparedStatement.getGeneratedKeys(). The first key is pretty much always the one you are interested in. For this statement:
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=3;
You can get the inserted or updated ID by calling:
Long key;
ResultSet keys = preparedStatement.getGeneratedKeys();
if (keys.next())
key = keys.getLong("GENERATED_KEY");
I may have either misunderstood how to use the ON DUPLICATE KEY syntax, alternatively my database structure needs some work but here goes.
I have a table (bookings-meta) which represents meta data associated with another table (bookings) , different rows in the bookings table may or may not have specific meta data associated with them in the other table.
The bookings-meta table has the following columns, meta_id (primary key), booking_id, key and value.
From my understanding, to use ON DUPLICATE KEY I need to know what in this case is the meta_id, often this isn't the case, I'm trying to simply push a key, value pair to the table using the booking_id, so if the particular key exists then its replaced otherwise its inserted.
At the moment I have a seperate query to try to select the row, if its found then I UPDATE, if not then its an INSERT.
Is there a way of doing an insert/update in one query without using ON DUPLICATE KEY or have I missed a trick with this one?
If possible, I'd drop the meta_id column entirely and turn booking_id and key into a composite primary key. That'll save space in your table, allow use of ON DUPLICATE KEY, and be cleaner in general.