将所有表插入另一个具有不同结构

时间:2018-06-18 13:30:25

标签: mysql

我正在使用mysql,我有一个包含以下内容的表 MySQL的>描述活动;

+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| year       | int(11)          | NO   | MUL | NULL    |                |
| month      | int(11)          | NO   |     | NULL    |                |
| project_id | int(10) unsigned | NO   | MUL | NULL    |                |
| user_id    | int(10) unsigned | NO   | MUL | NULL    |                |
| task_hour  | double(8,2)      | NO   |     | NULL    |                |
| from_otl   | tinyint(1)       | NO   |     | 0       |                |
| created_at | timestamp        | YES  |     | NULL    |                |
| updated_at | timestamp        | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
9 rows in set (0.01 sec)

这给了我特定年份,特定用户特定项目的特定月份,工作小时数。

我需要创建一个具有不同结构的表,其中包含来自最后一个表的数据。这将具有相同的列,但不是月份和任务小时,我将每个月作为列,并在此列中工作小时。

以下是我的尝试:

CREATE TEMPORARY TABLE temp_a
(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
year INT(10),
project_id INT(10),
user_id INT(10),
jan_com double(8,2),
jan_otl tinyint(1),
feb_com double(8,2),
feb_otl tinyint(1),
mar_com double(8,2),
mar_otl tinyint(1),
apr_com double(8,2),
apr_otl tinyint(1),
may_com double(8,2),
may_otl tinyint(1),
jun_com double(8,2),
jun_otl tinyint(1),
jul_com double(8,2),
jul_otl tinyint(1),
aug_com double(8,2),
aug_otl tinyint(1),
sep_com double(8,2),
sep_otl tinyint(1),
oct_com double(8,2),
oct_otl tinyint(1),
nov_com double(8,2),
nov_otl tinyint(1),
dec_com double(8,2),
dec_otl tinyint(1)
);
ALTER TABLE `temp_a` ADD UNIQUE( `year`,`project_id`, `user_id`);
INSERT INTO temp_a (`year`,`project_id`,`user_id`) VALUES (SELECT `year`,`project_id`,`user_id` FROM `activities` group by `year`,`project_id`,`user_id`);
select * from temp_a;

但它不接受插入......

我想要做的是首先将所有唯一年份,project_id,user_id填入此临时表,然后通过遍历活动表更新每条记录,并使用正确月份的值更新正确的行。

1 个答案:

答案 0 :(得分:2)

VALUES

中使用SELECT时,您需要删除INSERT INTO
  INSERT INTO temp_a (`year`,`project_id`,`user_id`) 
    (SELECT `year`,`project_id`,`user_id` FROM `activities` group by `year`,`project_id`,`user_id`);