Create a mysql conditional insert? - mysql

How can I check in table_1 if value_a of column_a (and where value_b of column_b = 'x') already exists in column_a of table_2? If it's not present insert it and create a new row for the missing value_a in table_2?
Update: (What seems to work is this:)
INSERT INTO products
(key, category)
SELECT key, category
FROM accounts
WHERE category = 'vegan'
AND NOT EXISTS (SELECT *
FROM products
WHERE accounts.key = products.key);

Why don't you transform the column into a primary key ? You'll just have to handle the duplicate entry error code
EDIT :
The solution here is to use SELECT instead of WHERE (thanks to degr)
INSERT INTO tableA(`id`,`column1`)
SELECT 44,'Value of Column1' -- The values you want to insert
WHERE NOT EXISTS(SELECT * FROM table2 WHERE id=40) -- check that there is no matching with the request
AND 1=1 --additional conditions
AND NOT EXISTS(SELECT * FROM Table3 WHERE id=44); --additional conditions

Related

MySQL QUERY TO DROP DATA WHICH ARE COMMON IN TWO DATABASES RDS (MYSQL DB'S)

e.g.:
**table 1**
name gender email
hemanth m test#gmail.com
rajesh m rajesh#gmail.com
kumar m kumar#gmail.com
**table 2***
name gender email
hemanthsai m testing#gmail.com
rajesh m rajesh#gmail.com
kumaras f kumaras#gmail.com
**expected result in table 1***
name gender email
hemanthsai m testing#gmail.com
rajesh m rajesh#gmail.com
kumaras f kumaras#gmail.com
this is just an example, in reality i have to update all the data with many columns at a time in mysql
What I've tried was
INSERT INTO table1 (NAME,gender, email) VALUES(?, ?, ?), (?, ?, ?)
ON DUPLICATE KEY UPDATE SET *; ### this didn""t worked ###
I need something like:
INSERT INTO table1 * ON DUPLICATE KEY UPDATE SET *;
If this didn't work then I thought of delete common values on one table using another table and then insert the left values into the deleted table, so I need query to delete common values on one table based on another table..
thanks in advance,
Create another table:
CREATE TABLE table3 (
name VARCHAR(50),
gender VARCHAR(50),
email VARCHAR(50));
Create a unique index on the new table:
CREATE UNIQUE INDEX index_name
ON table3 (name, gender, email);
Do INSERT IGNORE from both of table1 & table2:
INSERT IGNORE INTO table3 SELECT * FROM table1;
INSERT IGNORE INTO table3 SELECT * FROM table2;
Check your table3, it should't have any duplicates anymore.
Demo
P/S: If you want to only check duplicate email - and allow same user having multiple emails, you can skip creating unique index and make email column in table3 as PRIMARY KEY instead.
Have you tried INSERT INTO SELECT?
Example:
INSERT INTO `table1`
(`name`, `gender`, `email`)
SELECT t2.`name`, t2.`gender`, t2.`email`
FROM `table2` AS t2
ON DUPLICATE KEY UPDATE
`name`= t2.`name`,`gender` = t2.`gender`, `email` = t2.`email`
You also need to have a unique key which is common between table1 and table2. I assume that is the case.
EDIT
Taking your comment into account, what you are looking for might be REPLACE INTO.
REPLACE INTO `table1`
SELECT *
FROM `table2`
Please note that this operation doesn't update the old values, but actually deletes them. This means that the PRIMARY_KEY might be replaced if it has for instance auto_increment().
Also note that this is a heavy operation as the table needs to be reindexed for every delete operation.
You can read more about it here: http://code.openark.org/blog/mysql/replace-into-think-twice
Personally I would use INSERT INTO even if there are many columns

Insert into if not exists not inserting

INSERT INTO my_table (field_1, field_2)
SELECT val_1, val_2
FROM my_table
WHERE NOT EXISTS (SELECT field_1
FROM my_table
WHERE field_2 = val_2)
LIMIT 1
I can not use unique index on field_2 field.
I'm trying to insert if not exists a tuple with field2 = val_2.
Without the "where" clause, this insert.
With the "where" clause EVEN WHEN EMPTY TABLE, it won't insert.
Any help on that?
I guess val_1 and val_2 are not columns of the table, right?
They are values that you want to insert in the table.
So drop:
FROM my_table
and use:
INSERT INTO my_table (field_1, field_2)
SELECT val_1, val_2
WHERE NOT EXISTS (
SELECT field_1
FROM my_table
WHERE field2 = val_2
)
Solution is that check if key exist:
INSERT INTO my_table (field_1, field_2) ON DUPLICATE KEY INSERT IGNORE.
this question maybe useful.
First create a unique index on the column or columns that you don't want duplicated. I cannot tell if it is on both or just field_2:
create unique index unq_my_table_field_2 on my_table(field_2);
Then ignore the error using on duplicate key update:
INSERT INTO my_table (field_1, field_2)
VALUES (val_1, val_2)
ON DUPLICATE KEY UPDATE field_2 = VALUES(val_2); -- this is a no-op, because the value is already the same
The fact the your code doesn't work on an empty table has nothing to do with the WHERE clause but with using from my_table in the from clause. If there are no rows, then the query returns . . . no rows. No surprise there that nothing gets inserted.

SQL normalized data INSERT WHERE NOT EXISTS ; ON DUPLICATE KEY UPDATE

i am using MySql Workbench version 6.3.9 with mySql 5.6.35.
i have the following tables:
EQUIPMENT
eID | caochID | eName
COACH
coachID | coachName
SQLfiddle prepared http://sqlfiddle.com/#!9/e333d/1
eID is a primary key. there are multiple coachID's in different equipment, so there will be duplicate coachIDs with different equipment, but the eID will be unique as it is a primary key.
REQUIRED
i need to insert a row in the equipment table, if it does not already exist. If it exists, do nothing.
various posts online have pointed me towards two options:
a) INSERT...ON DUPLICATE KEY UPDATE...
b)INSERT...WHERE NOT EXISTS
PROBLEM i have problems with both of these solutions. for the first solution (ON DUPLICATE KEY UPDATE) the query inserts the row as required but does not update the existing row. instead it creates a new entry. for the second solution (WHERE NOT EXISTS) i get an error : SYNTAX ERROR: 'WHERE' (WHERE) is not a valid input at this position.
the sql query doesnt need to make any joins. i listed both tables so that you can see how they are related. the insert query i need will only insert for the equipment table.
You can insert by using a tmp table and ensuring that the same record is not existing from current table. Add limit 1 to ensure only one record is inserted. Below query will not insert since 1 and small ball exists.
INSERT INTO `Equipment` (`c_id`, `eName`)
SELECT * FROM (SELECT '1', 'small ball') tmp
WHERE NOT EXISTS (
SELECT c_id FROM Equipment WHERE `c_id`='1' and `eName` = 'small ball'
) LIMIT 1;
NOT EXISTS
insert into table2 (....) --- all if not columns ... destination
select ....
from table1 t1 --- source of data to check
where not exists (
select 1
from table2 t2
where t2.col = t1.col --- match source and destination table making sure table1 data is not in table2
)

How do I combine multiple conditions (exists and not exists) checks before inserting a new record in mysql?

I would like to build a query to insert a new record, after checking with an EXISTS and a NOT EXISTS condition in two different tables.
IF NOT EXISTS (SELECT 1 FROM `categories` WHERE categories.term_id = 123)
AND EXISTS (SELECT 1 FROM `terms` WHERE terms.id = 123)
THEN INSERT INTO `categories`(id, term_id, term_type_id)
VALUES ('', '123', '4')
Thanks in advance.
You an use indices to enforce this behavior.
EXISTS (SELECT 1 FROMtermsWHERE terms.id = 123)
To enforce this, define categories.term_id as a foreign key to terms.id.
That way you can not insert a term_id into the categories table if that is non existent in the terms table.
IF NOT EXISTS (SELECT 1 FROMcategoriesWHERE categories.term_id = 123)
To enforce this, you need to put a UNIQUE index on the categories.term_id column. This will block duplicate entries.
You can first check the desired record from the table with a select query. If the query returns the 0 rows then execute the insert statement otherwise no need to insert.

Single query for "INSERT INTO table if column value not found"

How can I use a single query for inserting table when a column value is not found.
eg/ i want to insert new user only when this username not found
what i doing now is issue 1 query to check for existing,
then another query if no existing found. total 2 query
INSERT INTO friends (memberID) SELECT 1 WHERE NOT EXISTS (SELECT memberID FROM friends WHERE memberID = 1)
You just need to add FROM DUAL
INSERT INTO friends
(memberid)
SELECT 1
FROM dual
WHERE NOT EXISTS (SELECT memberid
FROM friends
WHERE memberid = 1)
sql fiddle
How about this:
INSERT INTO YourTable (UserName)
SELECT x
FROM (SELECT 'New User Name' AS x) a
WHERE x NOT IN(SELECT UserName
FROM YourTable)
Since you only want one row with a given value you should enforce that with a UNIQUE constraint on the table, for example:
ALTER TABLE friends ADD UNIQUE (memberID);
After you do that, you can simply add the IGNORE keyword to your insert statements and it won't report an error and it won't insert a duplicate row if it already exists.
INSERT IGNORE INTO friends(memberID) VALUES(1);