开发者

Insert multiple values with different select criteria?

Is there a method for inserting multiple values when each value has to get some information first from another table?

For example I have two tables

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

data for the tables might look like this

interests example table

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

userinterests example table

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  

I find out that new user Hayley is interested in American Idol and beards

interests example table

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

I want to then update the userInterest database to add

id  user     interest_id
------------------------
4   h开发者_Python百科ayley   4          -- hayley is interested in American Idol  
5   hayley   5          -- hayley is interested in beards 

but I can't because I don't know what the interest id's are for American Idol and beards?

I want to insert all of Hayleys interests at once in some sort of multiple insert query.

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

I guess I would use SELECT somewhere but not sure where. Could someone provide me with an example of how to do this?


Use:

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

DEFAULT is because I assume that the id column is AUTO_INCREMENT.


Something like this?

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

Putting, instead of hayley, the hayley's id (you didn't say what is the type of it, so I don't know).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜