如何将1添加到上个月的记录并将其作为当前月份记录插入?

时间:2017-03-14 06:28:52

标签: mysql sql insert-update

我的表结构如下所示

id     month      year  dummyval
11     January    2017  1
12     January    2017  1
13     January    2017  2

我将在下个月插入此表,但我还想为每个id插入一个dummyval。就像表格应该是 -

id     month       year  dummyval
11     January     2017  1
12     January     2017  1
13     January     2017  2
11     February    2017  2
12     February    2017  2
13     February    2017  3

怎么做?请帮忙。

2 个答案:

答案 0 :(得分:1)

试试这个:

insert into table1 select id , 'February', 2017, dummyval+1 from table1  
where id=11;

你做的每个插入..

以下是一个例子:

mysql> select * from K3;
+------+------+
| name | val  |
+------+------+
| x    | 1    |
| y    | 2    |
+------+------+

INSERTING:

insert into K3 select 'g', val+1 from K3 where name='x';

插入后:

mysql> select * from K3;
+------+------+
| name | val  |
+------+------+
| x    | 1    |
| y    | 2    |
| g    | 2    |
+------+------+

您可以看到它已插入' g' 2,从x< s 1增加

答案 1 :(得分:1)

由于您在代码中存储了月份名称,因此您需要找到下个月的名称。为了保持简单(但有点冗长),我首先要定义一个辅助数据结构来保存基本的月份信息:

create table months (monthid int, monthname varchar(20));
insert into months (monthid, monthname)
select 1, 'January' union all
select 2, 'February' union all
select 3, 'March' union all
/*... all other months*/
select 12, 'December';

现在假设您表中的最大年月值(称之为数据')是2017年/ 1月。您可以使用以下代码查找下一年 - 月 - 虚拟组合并将其插入到您的表中,而无需事先知道您需要插入哪些记录(及其ID):

/* a temporary table to hold "next month" info. It should be avoided using a 
join, but I failed miserably in my attempt! */
create temporary table next_month (monthid int, monthname varchar(20), next_id int, next_name varchar(20));

insert into next_month (monthid, monthname, next_id)
select monthid, monthname, case when monthid = 12 then 1 else monthid + 1 end
from months;

update next_month set next_name = 
 (select monthname from months where months.monthid = next_month.next_id);

现在您已准备好插入新数据:

insert into data (month, year, dummyval)
select 
  next_month.next_name, 
  case when months.monthid = 12 then data.year + 1 else data.year end,
  data.dummyval + 1
from data join months on data.month = months.monthname 
join next_month on months.monthid = next_month.monthid
where data.month = 'January' and data.year = 2017;