[英]How do I insert data into a table where one of the values should be a foreign key from another table?
I wanted to update the post table (main table) with those data:我想用这些数据更新帖子表(主表):
User: "helper"
Title: "Title"
Description: "Description"
However, the post table userid column only accepts an integer (foreign keys from the user table (userid)), not username string itself.但是,post 表 userid 列只接受一个整数(来自用户表 (userid) 的外键),而不是用户名字符串本身。
How can I do this with INSERT, SELECT/WHERE query?如何使用 INSERT、SELECT/WHERE 查询执行此操作?
There are the tables.有桌子。
post邮政
+--------+--------+---------+-------------+
| postid | userid | title | description |
+--------+--------+---------+-------------+
| 1 | 1 | example | example |
+--------+--------+---------+-------------+
| 2 | 2 | example | example |
+--------+--------+---------+-------------+
| 3 | 3 | example | example |
+--------+--------+---------+-------------+
user用户
+--------+----------+--------+
| userid | username | roleid |
+--------+----------+--------+
| 1 | admin | 1 |
+--------+----------+--------+
| 2 | helper | 1 |
+--------+----------+--------+
| 3 | test | 2 |
+--------+----------+--------+
Here is what it should look like after the insertion:这是插入后的样子:
post邮政
+--------+--------+---------+-------------+
| postid | userid | title | description |
+--------+--------+---------+-------------+
| 1 | 1 | example | example |
+--------+--------+---------+-------------+
| 2 | 2 | example | example |
+--------+--------+---------+-------------+
| 3 | 3 | example | example |
+--------+--------+---------+-------------+
| 4 | 2 | Title | Description |
+--------+--------+---------+-------------+
Assuming postid auto-increments:假设 postid 自动递增:
insert into post (userid, title, description)
select userid, "Title", "Description"
from user
where username="helper"
Note that this will not insert anything if the given username is not found.请注意,如果未找到给定的用户名,这将不会插入任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.