使用另一个表中的值插入数据库行
基本上,我有两个表:images
和 servers
。当我想在 images
表中插入一行时,我需要指定 s_id
作为字段之一。问题是,我只有 name
,这是 servers
表中的另一个字段。我需要找到 s_id
属于 name
,然后在 images
上的 INSERT INTO
查询中使用它桌子。
也许这张图片会有所帮助: https://i.sstatic.net/DyMRJ.png
我只知道名称
字段,我需要使用它从 servers
表中的servers
表中获取 s_id
字段。当我有了它时,我可以在我的 INSERT INTO
查询中使用它,因为它是外键。
我发现了这个: http://www.1keydata.com/sql/sqlinsert.html
但它只是混乱我更是如此。
一种解决方案是运行两个查询。一种用于获取 s_id
,另一种用于运行插入查询。但如果有合理的替代方案,我想限制运行的查询量。
谢谢!
Basically, I have two tables: images
and servers
. When I want to insert a row into the images
table, I need to specify a s_id
as one of the fields. Problem is, I only have name
, which is another field in the servers
table. I need to find what s_id
belongs to name
, and then use that in my INSERT INTO
query on the images
table.
Maybe this image will help:
https://i.sstatic.net/DyMRJ.png
I only know the name
field from the servers
table, and I need to use it to get the s_id
field from the servers
table. When I have that, I can use it in my INSERT INTO
query, as it's a foreign key.
I found this:
http://www.1keydata.com/sql/sqlinsert.html
But it just confused me even more.
One solution would be to run two queries. One to get the s_id
, and one to run the insert query. But I'd like to limit the amount of queries I run if there's a reasonable alternative.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
INSERT ... SELECT
表单,如下所示(当然具有真实的列名称和值):我不知道您从哪里获得
u_id
、name
、filename
或images
的uploaded
列值,但您可以将它们作为文字值包含在SELECT
:这种事情会插入多个值如果
servers.name
不唯一。You can use the
INSERT ... SELECT
form, something like this (with real column names and values of course):I don't know where you're getting the
u_id
,name
,filename
, oruploaded
column values forimages
but you can include them as literal values in theSELECT
:This sort of thing will insert multiple values if
servers.name
is not unique.您应该能够执行类似的操作,但您需要填写 <> 中的项目以及您要插入的值。
这是 SQL Server 的语法,但我认为它也适用于 MySQL。
这是一篇关于 INSERT ... SELECT 语法 的文章
You should be able to do something like this, but you'll need to fill in the items in <> with the values you want to insert.
This is the syntax for SQL Server, but I think it will work with MySQL as well.
Here's an article on INSERT ... SELECT Syntax
请参阅我上面关于潜在数据完整性问题的评论。我假设您的服务器表中的名称字段有一个唯一的约束。
有几种方法可以实现此
INSERT
,我确信其中一些方法比其他方法更好。我并不声称我的方法是最好的方法,但它应该有效。我不知道您如何编写此查询,因此我将使用@FieldValue
来表示变量输入。我的方法是在插入语句中使用子查询来获取所需的数据。Please see my comment above regarding a potential data integrity issue. I am assuming that the name field in your server table has a unique constraint placed on it.
There are a couple of ways that you can approach this
INSERT
, and I'm sure that some are better than others. I make no claim that my way is the best way, but it should work. I don't know how you're writing this query, so I'm going to use@FieldValue
to represent the variable input. My approach is to use a subquery in your insert statement to get the data that you require.