将其他表中的数据插入到仅包含主键的表中

时间:2014-10-16 02:31:23

标签: sql compiler-errors primary-key sql-insert

我有三张桌子:

movies (MID, title)
actors (AID, name)
actor_role (MID, AID, roleName)

MID和AID是actor_role的外键。

我想将表格电影和演员的MID和AID数据插入到actor_roles中。 我使用以下代码:

insert into actor_role (rolename)
values
('aaaaa'),
('bbbbbbb'),
('ccccccccc'),
('ddd');

insert into actor_role (MID)
select MID from movies;

insert into actor_role (AID)
select AID from actors;

我收到了一个错误:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'MID', table 'MOVIE.dbo.actor_role'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Msg 515, Level 16, State 2, Line 8
Cannot insert the value NULL into column 'rolename', table 'MOVIE.dbo.actor_role'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Msg 515, Level 16, State 2, Line 11
Cannot insert the value NULL into column 'rolename', table 'MOVIE.dbo.actor_role'; column does not allow nulls. INSERT fails.
The statement has been terminated.

我如何解决错误?

2 个答案:

答案 0 :(得分:1)

将最后两个插入查询合并为一个:

insert into actor_role (MID, AID)
select MID, AID
from actors cross join movies;

然后,根据需要更新角色名称。

如果查询抱怨rolename列的空值,请在那里添加空格,直到您可以更新它....

insert into actor_role (MID, AID, rolename)
select MID, AID, ''
from actors cross join movies;

答案 1 :(得分:1)

那里有很多问题:

  • 显然,您的列roleNameMID不接受null值。这就是为什么在尝试插入Cannot insert the value NULL into column...时始终收到消息actor_role而未指定其中任何一列的内容。
  • 您正在尝试插入新数据,然后使用其他2个INSERT语句对其进行更新。这永远不会奏效。要实现这样的目标,您必须执行INSERT,然后执行UPDATE

所以解决方案是使用单个INSERT语句。类似的东西:

insert into actor_role (MID, AID, rolename)
values
(MID1, AID, 'aaaaa'),
(MID2, AID, 'bbbbbbb'),
(MID3, AID, 'ccccccccc'),
(MID4, AID, 'ddd');

AID的位置,我想,actorsMIDx中的演员的PK是movies中电影的PK。

修改

借用Charles解决方案,您可以通过执行以下操作来欺骗NOT NULL上的rolename约束:

insert into actor_role (MID, AID, rolename)
select MID, AID, "to complete..."
from actors cross join movies;

然后手动完成rolename列。