如何使用外键将数据插入表中

时间:2016-05-31 17:25:53

标签: mysql sql subquery

我目前遇到的问题是将值插入到数据库表中,该数据库表使用另一个表中的外键来将它们对齐在一起。表非常简单。一个保存有关项目的信息,另一个保存项目图像的值。他们在这里详细介绍。

projects

project_id int(50) PRIMARY KEY NOT NULL AUTO_INCREMENT,
project_name varchar(50) NOT NULL,
project_permitted timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "The date that the project took place.",
project_in varchar(50) NOT NULL COMMENT 'The place where the project took place (ie the city and state).',
project_type varchar(50) NOT NULL COMMENT 'The project type (ie residentual, commercial, etc).',
project_description longtext,
project_published timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

这是名为project_images

的第二个表
image_id int(50) PRIMARY KEY NOT NULL AUTO_INCREMENT,
project_id int(50),
image_url varchar(50) NOT NULL,
CONSTRAINT fk_projects FOREIGN KEY (project_id) REFERENCES projects(project_id)

我要做的是使用子查询使用projects表中的project_id将值插入到第二个表中。该查询如下所示:

insert into project_images (project_id, project_url, project_description) 
values (
(select project_id from projects where project_name = 'The Venue'),
"images/theVenue.png",
"The Venue: an appartment complex in Austin, Texas."
)

通过此查询,我不断收到错误消息

  

“你缺少逗号或结束括号”的效果   靠近project_id。

任何人都可以帮助或指出处理这种情况的最佳方法。

2 个答案:

答案 0 :(得分:0)

将您的查询修改为

insert into project_images (project_id, project_url, project_description) 
select project_id ,
"images/theVenue.png",
"The Venue: an appartment complex in Austin, Texas."
from projects where project_name = 'The Venue';

答案 1 :(得分:0)

在更多地研究这个问题之后,似乎你不能像我使用它来获取列的值那样使用子查询,但是,只要外键指向列,就可以直接插入列来自另一个已插入的表的主键。使用此查询的重点是PHP项目,所以我想我只是在项目中执行选择查询以获取其ID,然后将其添加到查询project_images表的sql中。这似乎是唯一的方法。