Mysql 是否插入具有不同选择条件的多个值?

Mysql 是否插入具有不同选择条件的多个值?,mysql,sql,insert,Mysql,Sql,Insert,当每个值必须首先从另一个表中获取一些信息时,是否有插入多个值的方法 例如,我有两张桌子 兴趣=id,主题1 userinterests=id,userid,interestid 表的数据可能如下所示 兴趣示例表 用户兴趣示例表 我发现新用户Hayley对《美国偶像》和《胡子》很感兴趣 兴趣示例表 然后我想更新userInterest数据库以添加 id user interest_id ------------------------ 4 hayley 4

当每个值必须首先从另一个表中获取一些信息时,是否有插入多个值的方法

例如,我有两张桌子

  • 兴趣=id,主题1
  • userinterests=id,userid,interestid
表的数据可能如下所示

兴趣示例表 用户兴趣示例表 我发现新用户Hayley对《美国偶像》和《胡子》很感兴趣

兴趣示例表 然后我想更新userInterest数据库以添加

id  user     interest_id
------------------------
4   hayley   4          -- hayley is interested in American Idol  
5   hayley   5          -- hayley is interested in beards 
但我不能,因为我不知道美国偶像和胡子的兴趣是什么

我想在某种多重插入查询中同时插入Hayley的所有兴趣

INSERT into userInterests   
  Values(hayley, --whatever the id from table interests for "American Idol")  
  Values(hayley, --whatever the id from table interests for "beards")
我想我会选择某处,但不确定在哪里。有人能给我举个例子说明如何做到这一点吗?

类似的例子

INSERT INTO userInterests VALUES
(hayley, SELECT id FROM interests WHERE subject1 = "American Idol"), 
(hayley, SELECT id FROM interests WHERE subject1 = "beards"); 
用hayley的id代替hayley(你没有说它是什么类型的,所以我不知道)。

使用:

INSERT INTO userInterests 
SELECT DEFAULT, 'hayley', i.id
  FROM INTERESTS i
 WHERE i.subject1 IN ('American Idol', 'beards')

DEFAULT
是因为我假设
id
列是
AUTO_INCREMENT

如果有3个主题而不是1个主题,查询会发生什么变化。我会在I.subject1和I.subject2分别出现在(‘美国偶像’、‘胡须’)和(‘美国偶像’、‘胡须’)的地方做吗?@daniel savage:这是可能的,但数据库设置(列)并不理想。@Elprup,你建议的编辑可能是一个新答案,或者是对这个答案的评论。这就是我要找的,但我想知道是否有更简洁的方法来编写它。您提供的语法错误,用查询替换hayley,从表用户(id,name)中选择hayley的id,方法是从name='hayley'所在的用户中选择id。我可以单独运行每个select查询,但将它们与insert into…values(选择1,选择2)组合使用似乎不起作用???@daniel savage:这就是为什么您在我提供的答案中使用语法。执行此操作时,select必须始终只返回一个值,因此您可以执行select MAX(id),例如,要显示DBMS,查询将始终为id返回合适的值。
INSERT into userInterests   
  Values(hayley, --whatever the id from table interests for "American Idol")  
  Values(hayley, --whatever the id from table interests for "beards")
INSERT INTO userInterests VALUES
(hayley, SELECT id FROM interests WHERE subject1 = "American Idol"), 
(hayley, SELECT id FROM interests WHERE subject1 = "beards"); 
INSERT INTO userInterests 
SELECT DEFAULT, 'hayley', i.id
  FROM INTERESTS i
 WHERE i.subject1 IN ('American Idol', 'beards')