How to insert into a mysql table only if not already existing? - mysql

A very simple question but I don't have the answer. I would like to insert a record into a table, but only if it doesn't already exist.
These are my tables:
table1
id
table2
idTable1 (FK: table1.id)
unik
I would like to insert into table2 only if the value to insert (unik) doesn't exist.
My first intuitions was to lock for update:
START TRANSACTION;
SELECT * FROM table2 WHERE unik = :unik FOR UPDATE;
IF (NOT EXISTS)
INSERT INTO table1 SET ...;
INSERT INTO table2 SET idTable1 = LAST_INSERT_ID(), ...;
COMMIT;
But if the value doesn't exist, it won't lock anything and if two scripts run together, they will insert the same record.
My second intuition was to insert on duplicate key:
INSERT INTO table1 SET ...;
INSERT INTO table2 SET idTable1 = LAST_INSERT_ID(), ... ON DUPLICATE KEY UPDATE idTable1 = idTable1;
But I already have to insert into table1 before table2 so what if I insert into table1 if finally nothing will be inserted into table2?

And why not doing something like:
START TRANSACTION
... DO SOME STUFF HERE
SAVEPOINT 'before_rollback';
INSERT INTO table1 SET ...;
INSERT INTO table2 SET idTable1 = LAST_INSERT_ID(), ... ON DUPLICATE KEY UPDATE idTable1 = idTable1;
# A record exists, rollback to remove record in table1
if (affected_rows == 1)
{
rollback 'before_rollback';
}
else
{
commit;
}
Be careful: maybe MySQL will not "release" the consumed autincrement (depending of your MySQL conf: https://dev.mysql.com/doc/refman/5.1/en/innodb-auto-increment-handling.html)

u can use count to see if there are or not like this
select count(*) thecount from table2 where unik = unikvalue
unikvalue is the value U want to search if exist or not
thecount here will have the number of row that founded
the general syntax is
SELECT COUNT(column_name) FROM table_name;

What about this? (or something like this)
INSERT INTO table1 (id) (
SELECT * FROM (SELECT NULL) TMP
WHERE NOT EXISTS (SELECT 1 FROM table2 WHERE uniq = :uniq)
)

Related

Update column IF exists else insert

I know about ON DUPLICATE USE KEY clauses. But I can not use it since I want to update and insert on non-unique column.
I have table1 and table2. I want to create a trigger on table1.
Pseudocode:
IF id_code for corresponding id_name from table1 is present in table2
then update record in table 2
else record in table2.
For Ex.
table1 has column1 id_code, column2 id_name
table2 has column1 id_code, column2 status
IF id_code for corresponding id_name from table1 is present in table2
UPDATE status column in table2.
ELSE insert id-code in table2
Best way would probably be to use a conditional statement, since as you said you are checking for a non unique value and thus cannot use ON DUPLICATE KEY:
IF EXISTS (SELECT id_code FROM table2 WHERE id_code = 'code from table1') THEN
UPDATE table2 SET status = 'new status' WHERE id_code = 'code from table1';
ELSE
INSERT INTO table2 (id_code, status) VALUES ('code from table1', 'new status');
END IF;
The only caveat here is that control structures are only valid in stored procedures, so you will need to put this in a stored procedure or a trigger.

Express: "If row exsists, remove from table 1 and insert into table 2. Return success." in mySQL

I have two tables, in which I want the following logic to occur:
if (any row with a specific id exist in table1)
{
1. Delete the row from table1
2. insert some data into the table2 with the id as one of the values
3. return success somehow (for me to verify in java)
}
else
{
return fail
}
I'm sure this can be expressed in a clever manner, but I can not figure out how!
Can somebody help me translate this from my procedural way of thinking?
Greetings
Depending on the language (java?) you're using:
PreparedStatement stmt = conn.prepareStatement("select * from table1 where id = ?");
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.first()) {
// same for insert and delete
insert into table2 (id, col2, col3) values(?, ?, ?);
delete from table1 where id = ?;
return true;
} else {
return false;
}
After some research I found this post. I slightly modified Mike's answer and ended up with this query:
START TRANSACTION;
INSERT INTO table1(col1, col2, col3, id)
SELECT * FROM (SELECT 'value1', 'value2,'valu3', 'id') AS tmp
WHERE EXISTS (
SELECT id FROM table2 WHERE id='123'
) LIMIT 1;
DELETE FROM table2 WHERE id='123';
COMMIT;
If id exists in table2, then the insert will be performed in table1 and deleted from table 2. Else, the insert will not be performed and the delete will not find any rows with the id 123 - so it will not be deleted. I also use START TRANSACTION and COMMIT to temporary disable AUTO COMMIT mode and thereby ensure that either all transactions occur, or none (in case of failure). I can then, in Java, check how many rows that where affected and see if the update where executed or not.

MySQL direct INSERT INTO with WHERE clause

I tried googling for this issue but only find how to do it using two tables, as follows,
INSERT INTO tbl_member
SELECT Field1,Field2,Field3,...
FROM temp_table
WHERE NOT EXISTS(SELECT *
FROM tbl_member
WHERE (temp_table.Field1=tbl_member.Field1 and
temp_table.Field2=tbl_member.Field2...etc.)
)
This worked for one scenario,But now my interest is to upload data directly from the program itself without using two tables. What i want is to upload the data which is not in the table. The sql i had in my head was like the following,
INSERT INTO tbl_member (SensorIdValue, DataTimeValue, DataInValue, IncompleteValue, SpiValue, InfoValue)
VALUES ('Sensor.org', '20121017150103', 'eth0','','','')
WHERE (SensorIdValue != 'Sensor.org'AND DataTimeValue != '20121017150103'AND DataInValue != 'eth0'AND IncompleteValue != ''AND SpiValue != ''AND InfoValue != '');
But it's wrong.. may i know the proper way of doing it please, Thank you very much :)
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
The first syntax is already correct.
you can use UPDATE command.
UPDATE table_name SET name=#name, email=#email, phone=#phone WHERE client_id=#client_id
INSERT syntax cannot have WHERE but you can use UPDATE.
The syntax is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
If I understand the goal is to insert a new record to a table but if the data is already on the table: skip it! Here is my answer:
INSERT INTO tbl_member
(Field1,Field2,Field3,...)
SELECT a.Field1,a.Field2,a.Field3,...
FROM (SELECT Field1 = [NewValueField1], Field2 = [NewValueField2], Field3 = [NewValueField3], ...) AS a
LEFT JOIN tbl_member AS b
ON a.Field1 = b.Field1
WHERE b.Field1 IS NULL
The record to be inserted is in the new value fields.
Example of how to perform a INSERT INTO SELECT with a WHERE clause.
INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2
merge into table2 chg
using table1 src on src.id = chg.id
when not matched then
insert (chg.id, chg.desc)
values (src.id, src.desc)
when matched then
update set chg.desc = src.desc;
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

How to insert into table 1 if not exists in table2?

I am new to mysql. I have a problem in inserting record to table1 if it does not exist in table2.I have 2 tables table1 and table2 in the form:
table1
dep_id start stop modified deleted
1 23456789 167921525 Yes No
2 34567812 345678145 Yes No
3 32789054 327890546 No No
table2
start stop modified deleted
23456789 167921525 No No
34567823 345678145 No No
32789053 727890546 No No
I am trying to insert values into table1's start and stop field values only if it does not exist in table2's "start" and "stop" columns. If it exists the I need to throw an error.
These tables do not have a primary key foreign key relationship.
I apologize for not knowing correct syntax but I have to do something like this in mysql and PHP.
Replace Into into table1 set 'start'=> $start,'stop' => $stop
(select 'start','stop' from table2 where table1.start and table1.stop not in table2.start and table2.stop);
How do I query these 2 tables to check if Table1.start and Table1.stop fields do not match with Table2.start and Table2.stop before inserting to table1?
You can do:
INSERT INTO table1 (start, stop)
SELECT a.*
FROM (SELECT 123456789 start, 234567890 stop) a
LEFT JOIN table2 b ON (a.start,a.stop) IN ((b.start,b.stop))
WHERE b.start IS NULL
Where 123456789 and 234567890 are your input values for start and stop respectively.
Then you can check it with rowCount or num_rows_affected based on what DB interface you're using (PDO, mysqli, etc.). If it's 0, then no record was inserted, otherwise, the insert occurred.
SQLFiddle Demo
I think this is what you want. This takes two values, $start and $stop, and only does the insert if it does not exist in table2:
insert into table1 (start, stop)
select *
from (select $start as start, $stop as stop) t
where not exists (select 1 from table2 where start = $start and stop = $end)
With parameterized values:
INSERT INTO table1 (start, stop)
SELECT a.*
FROM (SELECT ? start, ? stop) a
LEFT JOIN table2 b ON (a.start,a.stop) IN ((b.start,b.stop))
WHERE b.start IS NULL
This works but we do the insert through SQL statements.
Now, what would be the solution to insert the records by Interface? That is without SQL statement, with the restriction proposed in the problem.

MySQL Single Table Scan Update

Is there a way to accomplish a single table scan in MySQL with an UPDATE? The following is a standard example:
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
This is the ideal situation I'd like to happen in MySQL (But this is MsSQL):
UPDATE user SET (name = 'jesse') WHERE userid ='10001'
IF ##ROWCOUNT=0
INSERT INTO user (name) VALUES('jeeeeee')
It's sort of reversed in MySQL. You perform the insert, and if the key already exists, then update the row:
INSERT INTO Table1 (col1,col2,col3) VALUES (val1,val2,val3)
ON DUPLICATE KEY UPDATE col1 = val1, col2 = val2, col3 = val3;
This is predicated on you having a unique key for the table (which you do, right?)