SQL INSERT从SELECT [英] SQL INSERT from SELECT
问题描述
让我们说在我的代码我有用户名和一个值。现在我需要保存在db中,但我需要先获取对应的用户名的ID,因为这个表链接到pk / fk到users表。我该怎么做?
我知道你可以做一个INSERT(blah)SELECT等做,但是看起来像一个直的副本,我需要插入值与fk列作为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.
用户表:
[UserID(pk),UserName]
User Table: [UserID(pk), UserName]
头像表:
[UserID(fk),AvatarURL]
Avatar Table: [UserID(fk), AvatarURL]
我需要
INSERT INTO AvatarTable (UserID,AvatarURL)
VALUES(* userName ='theirname'*,'http://www.blah.com'的用户ID)
感谢
推荐答案
您可能正在寻找这个?:
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'
这篇关于SQL INSERT从SELECT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!