简体   繁体   中英

MySQL insert in one of two tables based on condition for one table

Consider two tables that have timestamp and data columns. I need to construct an SQL that does the following:

  • Insert data (unique timestamp and data column) in one table if timestamp value is not present in the table ("insert my data in table 1 for timestamp="12:00 1999-01-01" only if that timestamp is not present in table 1...)

  • Otherwise, insert very same data in different table without any checks, and overwrite if necessary (... otherwise insert same set of fields in table 2).

How I could possibly achieve this on SQL? I could do it using a client but this is way slower. I use MySQL

Run a query for your 2nd bullet first. ie insert data into table 2 if it is present in table 1

insert into table2 (data, timestamp)
select 'myData', '12:00 1999-01-01'
from table1
where exists (
    select 1 from table1
    where timestamp = '12:00 1999-01-01'
)
limit 1

Then run your the query for your 1st bullet ie insert into table1 only if the data doesn't already exist

insert into table1 (data, timestamp)
select 'myData', '12:00 1999-01-01'
from table1
where not exists (
    select 1 from table1
    where timestamp = '12:00 1999-01-01'
)
limit 1

Running both these queries will always only insert 1 row into 1 table because if the row exists in table1, the not exists condition of the 2nd query will be false and if it doesn't exist in table1, then the exists condition of the 1st query will be false.

You may want to consider creating a unique constraint on table1 to automatically prevent duplicates so you can use insert ignore for your inserts into table1

alter table table1 add constraint myIndex (timestamp);
insert ignore into table1 (data,timestamp) values ('myData','12:00 1999-01-01');

A regural INSERT statement can insert records into one table only. You have 2 options:

  1. Code the logic within the application
  2. Create a stored procedure within mysql and code the application logic there

No matter which route you choose, I would

  1. Add a unique index on the timestamp column in both tables.
  2. Attempt to insert the data into the 1st table. If the insert succeeds, everything is OK. If the timestamp exists, then you will get an error (or a warning depending on mysql confioguration). Your solution handles the error (in mysql see DECLARE ... HANDLER ... ).
  3. Insert the data into the 2nd table using INSERT INTO ... ON DUPLICATE KEY UPDATE ... statement, which will insert the data if the timestamp does not exists, or updates the record if it does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM