选择具有IF条件且未找到IF数据的数据,然后插入具有上次插入数据+1的数据


1.Select data from table
2.If data not found then insert data into that table with last record data using + 1
Table name = demo
Query = Select * from demo where user_id = test4 if not then insert into demo values ('test4','port1+1','port2+1','port3+1','port4+1');

示例:

+----+--------------------------------+------------+----------+-----------+---------+
| id | user_id                        | port1     | port2  | port3  | port4 |
+----+--------------------------------+------------+----------+-----------+---------+
|  1 | test1                          | 27        | 72     | 58     | 65   |
+----+--------------------------------+------------+----------+-----------+---------+

我需要这样的输出:

+----+--------------------------------+------------+----------+-----------+---------+
| id | user_id                        | port1     | port2  | port3  | port4 |
+----+--------------------------------+------------+----------+-----------+---------+
|  1 | test1                          | 27        | 72     | 58     | 65   |
+----+--------------------------------+------------+----------+-----------+---------+
|  2 | test4                          | 28        | 73     | 59     | 66   |
+----+--------------------------------+------------+----------+-----------+---------+

如果我理解正确,我的第一次尝试是

测试数据:

CREATE TABLE demo (
id INT AUTO_INCREMENT,
user_id VARCHAR(50) NOT NULL,
port1 int,
port2 int,
port3 int,
port4 int,
PRIMARY KEY (id)
);
insert into demo(user_id,port1,port2,port3,port4)
values('Test1',10,20,30,40),
('Test2',100,200,300,400)

insert into demo(user_id,port1,port2,port3,port4)
select 'Test4',port1+1,port2+1,port3+1,port4+1
from demo
where user_id != 'Test4'
and not exists (select 1 from demo where user_id = 'Test4')
order by id desc
limit 1

DbFiddle

最新更新