SQL关联实体

时间:2016-09-15 16:21:29

标签: mysql sql

我不知道为什么这段代码不起作用。引发语法错误,但据我所知,这应该有效。有人可以向我解释我做错了什么。

insert into playerteam(playerId, teamId) select id from player where 
  player.firstname='John' and select id from team where team.`name`='Swim Team';

3 个答案:

答案 0 :(得分:2)

使用如下:

INSERT INTO playerteam(playerId, teamId) 
SELECT (SELECT id FROM player WHERE player.firstname='John'), 
    (SELECT id FROM team WHERE team.`name`='Swim Team');

答案 1 :(得分:1)

此:

player.firstname='John' and select id from team where team.`name`='Swim  Team';
                     ^^^^^^^^^

您不能只将整个查询结果作为where子句返回。你必须以某种方式测试结果,例如

... AND EXISTS select ...
         ^^^^

答案 2 :(得分:1)

您的select查询不正确 - 您无法使用select ... AND select ...合并两个查询,您需要使用join

例如(但是你需要在这里添加连接的ON部分,以便连接两个表):

insert into playerteam(playerId, teamId) select player.id as playerId, 
  team.id as teamId from player inner join team on {ADD HERE COLUMNS TO JOIN BY}
where player.firstname='John' and  team.`name`='Swim Team';