[英]Using subqueries and data - MySQL
在mysqli中插入時,是否可以使用子查詢並同時在值中使用數據?
insert into articles(description) values('Information');
insert into blogs(blog, article_id) values('example.com/', SELECT LAST_INSERT_ID());
是的你可以。 只需將子查詢括在括號中即可。 例:
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)
但是正如@Pekka在上面的注釋中建議的那樣,在這種情況下,您甚至不需要子查詢。 這本來可以工作:
INSERT INTO blogs (blog, article_id) VALUES ('example.com/', LAST_INSERT_ID());
您可能要使用insert...select
代替。
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
所以這就像
insert into blogs(...) select 'example.com/', last_insert_id()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.