![](/img/trans.png)
[英]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.