如果所选列中有值,我该怎么做MySQL中的Insert with Select?

时间:2016-06-28 14:44:24

标签: mysql

我使用 MySQL 并且我有这样的表:

table: historic_v1
id | student_id | level1_start_date | level1_score | level2_start_date | level2_score
1  | 2345       | 2016-02-10        | 7.5          | 2016-04-15        | 5
2  | 5634       | 2016-03-05        | NULL         | NULL              | NULL
3  | 4885       | 2015-12-02        | 6            | 2016-01-05        | NULL

我想在表 historical_v2 中使用选择 historic_v1 中执行插入,但我只想要如果 historic_v1 中所选字段的值不是 NULL ,则在 historic_v2 中有一行。

我的意思是, historic_v2 表必须是这样的:

table: historic_v2
id | student_id | level | key        | date       | score
1  | 2345       | 1     | start date | 2016-02-10 | NULL
2  | 2345       | 1     | score      | NULL       | 7.5
3  | 2345       | 2     | start date | 2016-04-15 | NULL
4  | 2345       | 2     | score      | NULL       | 5
5  | 5634       | 1     | start date | 2016-03-05 | NULL
6  | 4885       | 1     | start_date | 2015-12-02 | NULL
7  | 4885       | 1     | score      | NULL       | 6
8  | 4885       | 2     | start_date | 2016-01-05 | NULL

在此示例中,学生 2345 historic_v2 表中有4行,学生 5634 只有1行而学生< em> 4885 3行。

如何使用选择 插入

PS:我知道这个结构不太好,但它只是我真正需要做的一个小例子,这个问题的解决方案对我很有帮助

提前致谢!

2 个答案:

答案 0 :(得分:2)

您可以使用选择联合

insert into historic_v2 (student_id, level, key , date , score)
select student_id, 1, 'start date', level1_start_date, null
from historic_v2
where level1_start_date is not null 
union 
select student_id, 1, 'score', null, level1_score
from historic_v2
where level1_score is not null 
union 
select student_id, 2, 'start date', level2_start_date, null
from historic_v2
where level2_start_date is not null 
union 
select student_id, 2, 'score', null, level2_score
from historic_v2
where level2_score is not null 

答案 1 :(得分:0)

类似帖子:INSERT with SELECT

你可以解决这样的问题..

INSERT INTO historic_v2 (...)
SELECT ...
FROM historic_v1
WHERE ...