[英]Insert and update in the same table
I have table 我有桌子
table1
****************************
id | start_date | end_date
1 30/06/2012 01/01/9999
When I insert a new row 当我插入一个新行
id | start_date | end_date
1 30/06/2012 26/06/2012 <- Now it is the start date of the next row2
2 26/06/2012 01/01/9999
The start date of insert row will became the end date of previous row and so on. 插入行的开始日期将成为上一行的结束日期,依此类推。
$sql = "INSERT INTO
table1(cate_id,task_id,obj,end_date,start_date,line)
SELECT
$cate_id ,
$task_id,
$obj,
'2011-02-28', -> this what I am trying to do
'9999-01-01', -> this what I am trying to do
line1
FROM
line_task
WHERE
line_task_id = (
SELECT
line_task_id
FROM
task
WHERE
task_id = 2
)";
When I tried something like this: 当我尝试这样的事情时:
insert into table1(cate_id,task_id,obj, start_date, end_date,line)
values (4,3,23, (Select max(end_date) from table1),end_date,'value_line');
I got message : 我得到了消息:
Error code 1093, SQL state HY000: You can't specify target table 'table1' for update in FROM clause
Line 1, column 1
Execution finished after 0 s, 1 error(s) occurred 执行完成0秒后,发生1个错误
Could told me how can I do this with mysql? 可以告诉我怎样才能用mysql做到这一点? Thanks
谢谢
Try this:: 尝试这个::
Set @max_date = Select max(end_date) from table;
Insert into table(id, start_date, end_date) values (id, @max_date ,end_date);
First,Get the last record end_date : 首先,获取最后一条记录end_date:
$sql = mysql_query("Select * from table1 ORDER BY ID Desc");
if ($row=mysql_fetch_array($sql))
{
$end_date=$row['end_date'];
}
then insert the new record with the previous $end_date. 然后使用之前的$ end_date插入新记录。
You can do it in one query 您可以在一个查询中执行此操作
INSERT INTO table1(cate_id,task_id,obj, start_date, end_date,line)
SELECT 4,3,23, MAX(end_date), end_date, 'value_line'
FROM table1;
Just have to follow proper syntax (second example): http://dev.mysql.com/doc/refman/5.5/en/insert-select.html 只需遵循正确的语法(第二个示例): http : //dev.mysql.com/doc/refman/5.5/en/insert-select.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.