Update column IF exists else insert - mysql

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.

Related

Excluding insert of specific rows when copying data in same table

I use code below to copy and insert data in same table in mysql:
INSERT INTO table (product_id, value, branch_id)
SELECT product_id, value, "71"
FROM table
WHERE branch_id = "53"
It works well for copying and inserting all data. In this case it copies rows with branch_id=53, adds new rows for every copied row and instead of 53 branch_id 71 is inserted.
But now I have some rows with branch_id=71 already inserted so I need to exclude insert of that existing data by stating something like WHERE branch_id = "53" AND product_id != "product_id that already exists in row with branch_id=71"
How to do that in MySQL?
If there's a unique composite index on (product_id, branch_id), you can use INSERT IGNORE. Then if it tries to create a duplicate row, it will just skip that entry silently.
If not, you can do:
INSERT INTO table (product_id, value, branch_id)
SELECT t1.product_id, t1.value, '71'
FROM table AS t1
LEFT JOIN table AS t2 ON t1.product_id = t2.product_id AND t2.branch_id = '71'
WHERE t1.branch_id = '53' AND t2.product_id IS NULL

Trigger or Transaction for multi table data update on new Insert

I have three tables with names table1, table2 and table3.
And skeletons are like below
table1 contains username and password data. Table2 contains his relation with other users.
So my requirement is when a user is registered, values will be inserted to table1. And user also will send list of other users to specify his references. For example when u1 is addded he has sent [u2, u3, u5]. As u2 and u3 are already registered those two users should be added to table2 as below. In table2 u1 - u5 should be added whenever u5 is registered.
So I am maintaing table3 to maintain unregistered users.
To be precise here is what I am trying to do.
when some user is added in table1 want to raise a trigger that will check table3 field_2 value with newly inserted value. Whatever rows are matching should be inserted into table2 as in u2 and u3 case.
Here is what I have tried but I am blurred on how to proceed further
create trigger transaction_state after update on table1
begin
insert into table2
select * from table1 where field_2 = /* newly updated */;
end;
Based on your input, I think there are two triggers to be written,
On Insert Trigger on table3, which would check if field_2 is already registered. If yes, then the record (field_1, field_2) would be inserted in table2.
On Insert Trigger on 'table1', which would select all rows where uid appears as field_2 and inserts all such rows to table2.
Let me know if this make sense and inline with your requirement and also the feasibility of it given that you are working third party database.
CREATE TRIGGER trigger1
AFTER INSERT ON table3
FOR EACH ROW
BEGIN
INSERT INTO table2
SELECT NEW.field_1, NEW.field_2
FROM table1
WHERE table1.uid = NEW.field_2
END;
CREATE TRIGGER trigger2
AFTER INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table2
SELECT table3.field_1, table3.field_2
FROM table3
WHERE table3.field_2 = NEW.uid
END;

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

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)
)

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?)