根据先前计算的值插入值

时间:2013-01-28 16:48:45

标签: mysql

我有下面的表名为'tasks_processes':

id| task_id | process_id | start | end  
 1| 2       | 43         | 0     | 250
 2| 2       | 82         | 250   | 500
 3| 2       | 21         | 500   | 750

因此,'start'和'end'列表示范围的边界,并且在任务中是唯一的。对于新进程,我需要执行INSERT SELECT查询,如下所示:

INSERT INTO tasks_processes (start,end,task_id,process_id) 
    SELECT 
        COALESCE ((SELECT MAX(end) FROM tasks_processes WHERE task_id=2),0) as new_val , 
        new_val + 250, 
        2, 
        12;

换句话说,我需要根据先前计算的值插入值。但MySQL给了我DatabaseError:没有这样的列:new_val

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您必须重复子查询,如下所示:

INSERT INTO tasks_processes (start,end,task_id,process_id) 
SELECT COALESCE ((SELECT MAX(end) FROM tasks_processes WHERE task_id=2),0), 
       COALESCE ((SELECT MAX(end) FROM tasks_processes WHERE task_id=2),0) + 250, 
       2, 
       12;

或者您可以使用以下内容:

INSERT INTO tasks_processes (start,end,task_id,process_id) 
SELECT new_val, new_val+250, 2, 12
FROM (SELECT coalesce(MAX(end), 0) as new_val FROM tasks_processes WHERE task_id=2) s;

答案 1 :(得分:0)

您无法使用new_val作为列, 试试这个

 INSERT INTO tasks_processes (start,end,task_id,process_id) 
SELECT 
    COALESCE ((SELECT MAX(end) FROM tasks_processes WHERE task_id=2),0) as new_val , 
    COALESCE ((SELECT MAX(end) FROM tasks_processes WHERE task_id=2),0) + 250, 
    2, 
    12;