Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

mysql - SQL INSERT from SELECT

Lets say in my code I have the users name, and a value. Now I need to save that in the db but I need to first get the ID corresponding to that users name because this table links with a pk/fk to the users table. How do I do it? I know you can do a INSERT (blah) SELECT etc to do it but that looks like a straight copy, i need to insert the value with the fk column as the result from a SELECT.

User Table: [UserID(pk), UserName]

Avatar Table: [UserID(fk), AvatarURL]

I need to INSERT INTO AvatarTable(UserID, AvatarURL) VALUES (*id of user where UserName = 'theirname'*, 'http://www.blah.com')

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You might be looking for this?:

insert into myDestTable (userid, name, value, othercolumns)
select us.userid, us.name,'myvaluefromcode', othercolumns
from users us 
where us.name = 'mynamefromcode'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...