2010-10-11 55 views
1

在插入mysqli時,是否可以使用子查詢並同時在值中使用數據?使用子查詢和數據 - MySQL

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

你試過了嗎?發生了什麼? – 2010-10-11 11:02:41

+2

提示:調用某個函數時不需要'SELECT' – 2010-10-11 11:03:28

+0

沒有任何事情顯示錯誤。 – user453984 2010-10-11 13:29:19

回答

3

是的,你可以。只需將子查詢包裝在括號中即可。例如:

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()); 
+0

非常感謝。 – user453984 2010-10-11 13:35:03