开发者

Using subqueries and data - MySQL

Is it possible to use subquery and at the same time use d开发者_JS百科ata in values when Inserting in mysqli?

insert into articles(description) values('Information');
insert into blogs(blog, article_id) values('example.com/', SELECT LAST_INSERT_ID());


Yes you can. Simply wrap the subquery in parenthesis. Example:

CREATE TABLE articles (id int not null primary key, description varchar(50));
Query OK, 0 rows affected (0.06 sec)

CREATE TABLE blogs (id int not null primary key, blog varchar(50), article_id int);
Query OK, 0 rows affected (0.06 sec)

INSERT INTO articles (description) VALUES ('Information');
Query OK, 1 row affected, 1 warning (0.04 sec)

INSERT INTO blogs (blog, article_id) VALUES ('example.com/', (SELECT LAST_INSERT_ID()));
Query OK, 1 row affected, 1 warning (0.04 sec)

But as @Pekka suggested in the comments above, in this case, you do not even need a subquery. This would have worked:

INSERT INTO blogs (blog, article_id) VALUES ('example.com/', LAST_INSERT_ID());


You may want to use insert...select instead.

http://dev.mysql.com/doc/refman/5.1/en/insert-select.html

So it would be something like

insert into blogs(...) select 'example.com/', last_insert_id()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜