mysql insert if not exists doesn't work creating duplicate keys - mysql

although i am using mysql "insert ignore" statement
to insert a row to a table called software
i want to make sure that i will not insert a software that already exists in the table.
my table called software and i want to insert
new software to this table but if its already
exists in the table,i want the skip the insert
my table looks like this:
+----+-----------+
| id | name |
+----+-----------+
| 1 | software1 |
| 2 | software2|
| 3 | software3 |
| 4 | software4 |
| |
+----+-----------+
i used "insert ignore" but still its creates duplicate keys
MariaDB [db]> insert ignore into software values (5,'software4');
now i can see that there is a duplicate software4 key
+----+-----------+
| id | name |
+----+-----------+
| 1 | software1 |
| 2 | software2|
| 3 | software3 |
| 4 | software4 |
| 5 software4
+----+-----------+
although i can see similar question here:
mysql insert only if not exists doesn't work
as i am mysql newbie it didn't help me

check: https://mariadb.com/kb/en/library/insert-ignore/
"By using the IGNORE keyword all errors are converted to warnings, which will not stop inserts of additional rows."
If you do not want to have duplicate entries in name, make them UNIQUE:
CREATE TABLE t1 (x int UNIQUE);

First Make the name column unique so you are sure that there are no duplicate entries:
ALTER TABLE software ADD UNIQUE (name);
And then use INSERT IGNORE... which will only INSERT if it still doesn't exist

INSERT INTO software (id, name)
SELECT 4, 'software4'
FROM software
WHERE NOT EXISTS(
SELECT 1 FROM software WHERE name = 'software4'
) LIMIT 1;
DEMO
This will insert the record, only when the name is not already existing.

Related

Use ON DUPLICATE KEY UPDATE to update row with MySQL

I've the following table structure:
Table ___Availabilities :
|--------|------------|------------|------------|
| AVA_Id | AVA_RoomId | AVA_Date | AVA_Status |
|--------|------------|------------|------------|
| 1 | 47 | 2019-03-11 | NoData |
| 2 | 48 | 2019-03-22 | Book |
| 3 | 48 | 2019-03-23 | Book |
|--------|------------|------------|------------|
I want to UPDATE the AVA_Status only if AVA_RoomId and AVA_Date are know in a row of the table. If not, INSERT a new row.
So my query is this one:
INSERT INTO ___Availabilities
(AVA_Id, AVA_RoomId, AVA_Date, AVA_Status)
VALUES('', '103', '2019-04-04', 'Open')
ON DUPLICATE KEY UPDATE
`AVA_RoomId`='47',
`AVA_Date`='2019-03-11'
But it doesn't work as it added a new row whereas it should update the row where AVA_RoomId = 47 and AVA_Date = 2019-03-11.
Why my query is not working please ?
Thanks.
Assuming there is a UNIQUE INDEX(AVA_RoomId, AVA_Date)
You might want to update the AVA_Status when the combination of room and date already exists:
INSERT INTO ___Availabilities
(`AVA_RoomId`, `AVA_Date`, `AVA_Status`)
VALUES('103', '2019-04-04', 'Open')
ON DUPLICATE KEY UPDATE
`AVA_Status` = VALUES(`AVA_Status`),
As #Barmar already explained, if not already done, you can still add an index after table creation:
ALTER TABLE `___Availabilities`
ADD UNIQUE INDEX `uq_room_date` (`AVA_RoomId`, `AVA_Date`)
;

Performing INSERT using SELECT statement with WHERE IN clause attempts to insert values not returned by SELECT statement alone

I'm trying to insert values into an empty table using the following MySQL statement:
INSERT INTO buildings (name, description)
SELECT structures.name, structures.description
FROM structures
WHERE structures.structure_id IN (1, 2, 3, 4)
AND structures.deleted_at IS NULL;`
When I execute the SELECT statement alone, the expected rows are returned. However, when combined with the INSERT, I receive a "data truncation" error because the statement appears to be trying to insert a row that has been soft deleted and so has had its ID changed to something like 1__DEL__2016-06-21 18:19:53. As evidence that this is what's happening, removing 1 from the WHERE IN clause prevents the error.
The structures table looks like this:
+-----------------------------+----------+----------------------------------+----------------------+
| structure_id | name | description | deleted_at |
+-----------------------------+----------+----------------------------------+----------------------+
| 1 | House | Place for people. | null |
+-----------------------------+----------+----------------------------------+----------------------+
| 1__DEL__2016-06-21 18:19:53 | Home | Another name for house. | 2016-06-21 18:19:53 |
+-----------------------------+----------+----------------------------------+----------------------+
| 2 | Barn | Place for animals. | null |
+-----------------------------+----------+----------------------------------+----------------------+
| 3 | Outhouse | Place to go when you need to go. | null |
+-----------------------------+----------+----------------------------------+----------------------+
So, I'm curious (a) why this is happening, and (b) how I might be able to insert the data the I need without removing the soft-deleted entries from the source table.
What seemed particularly odd to me is that the WHERE IN clause seems to be match both 1 and 1__DEL__2016-06-21 18:19:53, as if it's not picking out exact matches.
Thanks.
Since the structure_id column in the Where clause is varchar, you should surround the values in the IN clause with quotes.

Deleting almost duplicate rows in MySQL?

I have seen a few different answers for this question, but none really hit exactly what I needed to do in MySQL.
I did find a thread for MS SQL that is exactly to what I need to do here but nothing min MySQL.
Data Example
+--------+----------+--------+
| Col1 | Col2 | UniqueID |
+--------+----------+--------+
| Peaches| Outdoor | 1 |
| Peaches| Outdoor | 2 |
| Apples | Indoor | 3 |
| Apples | Indoor | 4 |
+--------+----------+--------+
Desired Output
+--------+----------+--------+
| Col1 | Col2 | UniqueID |
+--------+----------+--------+
| Peaches| Outdoor | 1 |
| Apples | Indoor | 3 |
+--------+----------+--------+
Your way is OK. You only forgot the KEYWORD TABLE
CREATE TABLE NewTable AS SELECT Col1,Col2 ,MAX(col3) FROM t GROUP BY Col1,col2
but the structure can be different from the original table
Do this way:
CREATE TABLE NewTable like t;
then add a unique key:
ALTER TABLE NewTable ADD KEY (Col1,col2);
and now copy old data in new table with ON DUPLICATE KEY UPDATE
INSERT INTO NewTable
SELECT *
from t
ON DUPLICATE KEY UPDATE Col3=GREATEST(Col3,VALUES(Col3));
so you copy every row and the duplicates tests for maximum
Im going to post the answer to the answer provided above so its clear...it is just one simple query:
CREATE NewTable AS SELECT Col1,Col2 ,MAX(col3) FROM t GROUP BY Col1,col2
Just querying max was the trick...so simple.
Thank you!

MySQL: Copy data from TableA:FieldA to TableB:FieldB matching common UID field

I didn't see this exact question asked. Most people seem to want to sync. I just need a one-time copy.
MySQL version is 5.5.35.
In my MySQL database I need to one-time copy data from TableA:FieldA to TableB:FieldB while matching a common UID field — TableA:UID and TableB:UID are the related fields.
More specifically I am copying Employee ID from one table to a different field in another table, and both tables have Contact ID in common. So obviously I need TableA:UID=1's Employee Number to appear in TableB on the correct row where TableB:UID=1.
Thanks.
UPDATED: Tested the solution, got an error 1442
UPDATE civicrm_value_member_fields_1
SET civicrm_value_member_fields_1.aft_id_43 =
(SELECT civicrm_contact.external_identifier FROM civicrm_contact
WHERE civicrm_contact.id = civicrm_value_member_fields_1.entity_id)
alt version of the above:
UPDATE `civicrm_value_member_fields_1`
SET `aft_id_43` =
(SELECT `external_identifier` FROM `civicrm_contact`
WHERE `id` = `entity_id`)
both error 1442:
#1442 - Can't update table 'civicrm_contact' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
The following example should help.
create table A(id int,cid int);
create table B(id int,cid int);
insert into A values(6,1);
insert into A values(7,2);
insert into A values(8,3);
insert into A values(9,4);
insert into B(cid) values(1);
insert into B(cid) values(3);
insert into B(cid) values(4);
Table A
| ID | CID |
|----|-----|
| 6 | 1 |
| 7 | 2 |
| 8 | 3 |
| 9 | 4 |
Table B
| ID | CID |
|--------|-----|
| (null) | 1 |
| (null) | 3 |
| (null) | 4 |
The UPDATE query will update B's id field referring A's id field.
update B set B.id = (select A.id from A where A.cid = B.cid);
Table B
| ID | CID |
|----|-----|
| 6 | 1 |
| 8 | 3 |
| 9 | 4 |
The error can be sidestepped by first creating a temporary table - it will have all the data you need but not have the functions/triggers that impede the step.
Also, once the table is set then a JOIN statement is a more efficient representation of the action and should run more quickly as well.
CREATE TEMPORARY TABLE contact_dupe SELECT id, external_identifier FROM civicrm_contact;
UPDATE civicrm_value_member_fields_1 AS cs
JOIN contact_dupe AS cd ON cd.id=cs.entity_id
SET cs.aft_id_43=cc.external_identifier;

INSERT / UPDATE SQL random & unique VARCHAR

I need to be able to INSERT/UPDATE UNIQUE RANDOM UTF8 ALPHANUMERICAL VARCHAR 55 into a table field called 'key'.
Can't find out any good query example, does anyone can show me or link me something?
This answer is based on mysql.
This select will create 55 char long random strings:
select substr(concat(md5(rand()),md5(rand())),1,55);
to fill your table column you might want to try out:
create table example (keycol varchar(55));
insert into example (keycol) values (substr(concat(md5(rand()),md5(rand())),1,55));
The result will be:
select keycol from example;
+---------------------------------------------------------+
| keycol |
+---------------------------------------------------------+
| 4517f4be669301a4a529b53fc18d646dec42d4d07d911d33a67c863 |
| 3caa1c98f0f9ee39515aa6f4ddb3f84fa41abd5392f610c5d24bcd9 |
| 8e52cb4ce29e58514671c9b68f19832f26ddf53f277621ac420bd2e |
| 3adcccfb6cb729ce1c0a14fb75f6fd54f58992dc0751527c969e007 |
| c28c5879589dc90f4fb0963673e5668fa5789d325423ba043e0243b |
| 8f7a2af97d73261008f0d0d7249480fde56a3a91f2ce6e8bf0b0070 |
| ff4f74f25b92da3eaab282218c23a75d4cfa77c8f8bfdf74d7ebdf9 |
+---------------------------------------------------------+