3

我有下表称为“tasks_processes”:

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

因此,“开始”和“结束”列代表范围的界限,并且在任务中是唯一的。对于新进程,我需要像这样执行 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: no such column: new_val

如何解决这个问题呢?

4

2 回答 2

1

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

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;
于 2013-01-28T16:51:41.913 回答
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;
于 2013-01-28T16:52:52.907 回答