Insert missing data only in MySQL - mysql

I have two tables, the first table has 400 rows. The second table holds the same records with the same count. Now the first table row count increases to 450. I want to insert only those 50 new rows into the second table. I don't need to update the first 400 records.
I am setting the unique index for the particular field (like empid). Now when I insert the first table data it returns the following error:
Duplicate entry 'xxxx' for key 'idx_confirm'
Please help me to fix this error.
Am using the below code to insert the record. But it allows duplicate entry..
insert ignore into tbl_emp_confirmation (fldemp_id,fldempname,fldjoindatefldstatus)
select fldempid, fldempname,DATE_FORMAT (fldjoindate,'%Y-%m-%d') as fldjoindate,fldstatus from tblempgeneral as n;

Modify your INSERT ... statement to INSERT IGNORE ....
See for example this post for an explanation.
You need to make sure that you have a unique index that prevents any duplicates, such as on the primary key.

Related

MySQL Error: Duplicate entry 'xxx' for Primary Key

I have table MySQL with Primary Key Composed of 2 fields, as below
Already existing records in the table are:
The INSERT query I am issuing is:
When I run the query:
INSERT INTO `case_data`
VALUES ('WCD/2016/1000017', 2, '2016-09-29', 'WCD',***********************
The error message displayed is:
[Err] 1062 - Duplicate entry 'WCD/2016/1000017' for key 'PRIMARY'
Am I violating the Primary Key constraint?
Thanks in advance.
You could check if the primary key values of a row you are trying to insert already exist in a table:
SELECT COUNT(*)
FROM case_data
WHERE caseno = 'WCD/2016/1000017' AND iteration = 2;
If it returns 0 then you will not violate the PK constraint and are safe to insert the row you wish (assuming there are no additional checks, triggers, constraints). Otherwise it will return 1 which means that you already have a row with values in those columns, thus you would violate uniqueness of the row which is not allowed.
When it returns 0 just issue an INSERT command. Also, remember to specify your column tables within the statement to make sure every value from your VALUES is being put within the right column of your destination table:
INSERT INTO case_data (caseno, iteration, casedate, casetype)
VALUES ('WCD/2016/1000017', 2, '2016-09-29', 'WCD');
Avoid using backticks around your column and table names if they don't contain alternative characters like commas or spaces. This will make your code more readable and definitely speed up your writing time.

Delete Query MySQL : Column Count Doesn't Match Value Count at Row 1

I am trying to delete all rows from a table with a particular id.
my query is:
DELETE FROM table_name WHERE x_id='46';
the error returned is:
#1136 - Column count doesn't match value count at row 1
my table has a composite primary key x_id is one of the columns in the primary key.
Please Help!
That error is strange for a delete statement. It is most likely coming from badly written trigger that is being executed as a result of the delete.
This error would most likely be encountered on an insert statement such as the following:
insert into foo(bar, baz)
select bar, baz, foobar, 2
from myTable
Note how the insert statement specifies 2 columns, but provides 4 values.
You might try to provide a second value to the delete query to match the composite index for the row.
DELETE FROM CPI
WHERE (CountryID, Year) IN (('AD', 2010), ('AF', 2009), ('AG', 1992))
Cause:
You may have a trigger on this table, then you changed the table structure.
Now, you may get this error when you delete, insert, or update in this table (depending on the trigger event you specified).
Solution:
To solve this issue, you have to update the trigger as well, the number of columns of the trigger should match the number of the columns of the table.

insert on duplicate key update

I would like to use "insert on duplicate key update" in a query to either insert a new row if it does not exist or update a row if it does. What I can not seem to figure out is how to use this if I do not have the unique id (because the row has not yet been created, and this ID will be autoincremented upon insert)
insert into foodchoices (unique,notunique) values (Idonthavethis,'test')
on duplicate key update notunique = 'stuff';
Now, in this example above, where it says "Idonthavethis", I do not have any unique value for this field, because it has not yet been inserted as a row. However, I do expect that this inserts somehow, I just dont know how. I expect it to act like this:
insert into foodchoices (notunique) values ('test')
BUT, if it is a field that does already exist, I WILL have that unique value. Is there some form of wildcard or something I can use for when I do not have the unique value?
I believe the answer to this is addressed in the MySQL docs:
If a table contains an AUTO_INCREMENT column and INSERT ... UPDATE inserts a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. If the statement updates a row instead, LAST_INSERT_ID() is not meaningful. However, you can work around this by using LAST_INSERT_ID(expr). Suppose that id is the AUTO_INCREMENT column. To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;
I think what you just might try to do is select the row with the value you have (if exists then update) otherwise insert. It's just one more sentence.
I just don't see how can you compare an existing value that you just don't have (the generated ID). Plus, if the ID is DB seeded how it'll be duplicated?
May be you need to alter your table structure for adding any constraint to "notunique" column. So you can:
insert into foodchoices (notunique) values ('test') on duplicate key update columntostoreyouruniqueid = unique;
if notunique has no constaint then it mean that you will have uniqueid as set. So it has to double query.

Does mySql have an update/insert combo which inserts if the update fails?

I'm not optimistic that this can be done without a stored procedure, but I'm curious if the following is possible.
I want to write a single query insert/update that updates a row if it finds a match and if not inserts into the table with the values it would have been updating.
So... something like
updateInsert into table_a set n = 'foo' where p='bar';
in the event that there is no row where p='bar' it would automatically insert into table_a set n = 'foo';
EDIT:
Based on a couple of comments I see that I need to clarify that n is not a PRIMARY KEY and the table actually needs the freedom to have duplicate rows. I just have a situation where a specific entry needs to be unique... perhaps I'm just mixing metaphors in a bad way and should pull this out into a separate table where this key is unique.
I would enforce this with the table schema - utilize a unique multi-column key on the target table and use INSERT IGNORE INTO - it should throw an error on a duplicate key, but the insert will ignore on error.

Multiple Column Duplicate Entry Check MySQL

I'm aware that you can create a unique column in your MySQL table, but I'm actually looking to compare TWO columns.
So if I had records like:
Time User Table
10:00pm Fred 29
11:00am Bob 33
I COULD insert a new record with the time 10:00pm and table 33 but not 10:00pm table 29.
I know I could run a query and then nullify my ability to insert a new record if I had results from that query based on comparing those two fields, but I'm wondering if there is a more elegant solution wherein I can get a duplicate entry error from MySQL on the INSERT and save myself a few lines of code.
You can create a unique index that incorporates both columns:
CREATE UNIQUE INDEX idx_time_and_table ON reservations (`Time`, `Table`);
This will block any inserts for the same pairing provided both values are not NULL. Having a NULL value side-steps the unique checking.
You're also using reserved SQL keywords for your column names which you might want to change.
Try using a composite unique constraint across both columns:
ALTER TABLE your_table ADD UNIQUE(`Time`, `Table`);
Now any rows attempting to be added that have matching values will force MySQL to throw an error, which you can test for in your app.
Create an unique index based on the columns you want to be unique:
CREATE UNIQUE INDEX index_name ON table_name ( column1, column2,...);