[英]MYSQL: How to insert rows in a table based on a condition of other two tables
[英]MySQL insert in one of two tables based on condition for one table
考慮兩個具有時間戳和數據列的表。 我需要構造一個執行以下操作的SQL:
如果表中沒有時間戳值,則在一個表中插入數據(唯一的時間戳和數據列)(僅當時間戳不存在於表1中時,“在表1中為timestamp =“ 12:00 1999-01-01插入我的數據”)表格1...)
否則,在不做任何檢查的情況下將非常相同的數據插入不同的表中,並在必要時覆蓋(...否則,在表2中插入相同的字段集)。
如何在SQL上實現此目標? 我可以使用客戶端來執行此操作,但是速度較慢。 我使用MySQL
首先運行第二個項目符號的查詢。 即,如果表1中存在數據,則將其插入表2中
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
然后對第一個項目符號運行查詢,即僅在數據不存在時才插入到table1中
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
運行這兩個查詢將始終僅將1行插入到1個表中,因為如果該行存在於table1中,則第二個查詢的not exists
條件將為false;如果該行在table1中不存在,則第一個查詢的exists
條件將是錯誤的。
您可能要考慮在table1上創建唯一約束,以自動防止重復,因此可以對表1中的insert ignore
使用insert ignore
alter table table1 add constraint myIndex (timestamp);
insert ignore into table1 (data,timestamp) values ('myData','12:00 1999-01-01');
常規INSERT
語句只能將記錄插入一個表中。 您有2個選擇:
無論您選擇哪種路線,我都會
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.