使用不同的选择条件插入多个值?

时间:2011-05-13 01:39:24

标签: mysql sql insert

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

例如,我有两个表

  • interests = id,subject1
  • userinterests = id,userid,interestid

表的数据可能如下所示

兴趣示例表

id  interests
-------------
1   cats  
2   mysql  
3   php  

userinterests示例表

id  user   interest_id
----------------------
1   dan    1            -- dan is interested in cats  
2   johan  2            -- johan is interested in mysql   
3   joe    1            -- joe is interested in cats  

我发现新用户Hayley对美国偶像和胡须很感兴趣

兴趣示例表

id  interests
-------------
1   cats  
2   mysql  
3   php  
4   American Idol  
5   beards  

我想更新userInterest数据库以添加

id  user     interest_id
------------------------
4   hayley   4          -- hayley is interested in American Idol  
5   hayley   5          -- hayley is interested in beards 

但我不能,因为我不知道对于美国偶像和胡须的兴趣是什么?

我希望在某种多插入查询中同时插入所有Hayleys的兴趣。

INSERT into userInterests   
  Values(hayley, --whatever the id from table interests for "American Idol")  
  Values(hayley, --whatever the id from table interests for "beards")

我想我会在某处使用SELECT,但不知道在哪里。有人能为我提供一个如何做到这一点的例子吗?

2 个答案:

答案 0 :(得分:1)

使用:

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

DEFAULT是因为我认为id列是AUTO_INCREMENT

答案 1 :(得分:0)

这样的东西?

INSERT INTO userInterests VALUES
(hayley, SELECT id FROM interests WHERE subject1 = "American Idol"), 
(hayley, SELECT id FROM interests WHERE subject1 = "beards"); 

如果(你没有说出它的类型是什么,我不知道),而不是hayley,而不是{{1}}。

相关问题