我想创建一个MySQL程序插入表中并删除其他表...
我的程序:
Python
错误讯息:insert ignore into old_events (select * from events where start < now());
delete from events where start < now();
答案 0 :(得分:1)
使用INSERT INTO SELECT
时删除()
:
insert ignore into old_events
select *
from `events`
where `start` < now();
考虑使用列列表而不是*
:
insert ignore into old_events(col1, col2, ...)
select col1, col2, ...
from `events`
where `start` < now();
请记住,now()
与时间有关,您应将其结果存储在变量中以进行比较。在INSERT
和DELETE
now()
之间可能会发生变化。
答案 1 :(得分:0)
当我看到您插入查询时,您将数据插入old_events列,但您从事件表中选择所有列。因此,您只能选择要插入old_events列的列
INSERT IGNORE INTO old_events
SELECT * FROM events
WHERE start < now();
DELETE FROM events WHERE start < now();
在我的系统中,我创建了两个表
create table events( id int,event_name varchar(20), start timestamp default current_timestamp);
create table old_events( id int,event_name varchar(20), start timestamp default current_timestamp);
然后将6行插入events
表
insert into events(id,event_name, start) values
(1,'event1','2016-02-18'),
(2,'event2','2016-02-19'),
(3,'event3','2016-02-20'),
(4,'event4','2016-02-21'),
(5,'event5','2016-02-22'),
(6,'event6','2016-02-23');
并执行select query,其中start小于current time
SELECT * FROM events
WHERE start < now();
返回5行 see example
但是在sqlfiddle中,我们只能运行select查询,所以在我的系统中执行以下查询并成功执行并且将5行插入到old_events中,其中start小于current time
INSERT INTO old_events
SELECT *
FROM EVENTS WHERE START < NOW();
之后,我从old_events表中选择行,返回5行
select * from old_events;
之后我执行删除查询并从事件表中删除5行
DELETE FROM EVENTS WHERE START < NOW();
在所有步骤之后,我执行另外两个查询,从events and old_events table
select * from events; // its return 1 row where start is greater than now()
select * from old_events; // its return 5 row where start is less than now()