2012-04-23 172 views
1

比方說,我想插入這樣的數據:一個查詢插入多行多列

Row 1: People = '40', Places = '15' 
Row 2: People = '5', Places = '10' 

我明白,這是你將怎樣執行上面:

mysql_query("INSERT INTO mytable(`People`, `Places`) 
VALUES ('40', '15'),('5', '10')"); 

但什麼如果我想用一個查詢插入兩個以上的列?如果要插入的數據是這樣的:

Row 1: People = '40', Places = '15' 
Row 2: People = '5', Places = '10' 
Row 3: Things = '140', Ideas = '20' 
Row 4: People = '10', Things = '5', Ideas = '13' 

我似乎無法在其他地方找到這樣的問題。

+0

我想你不能用一個查詢做到這一點! – Anji 2012-04-23 19:05:17

回答

3

離開列你不wanto以填補null

INSERT INTO mytable(`People`, `Places`, Things, Ideas) 
VALUES ('40', '15', null, null),(null, null, 100, 20) 
+0

不錯,簡單,http://www.php.net/manual/en/function.mysql-query.php#101945 – Alex 2012-04-23 19:08:18

3
mysql_query("INSERT INTO mytable(`People`, `Places`, `Ideas`, `things`) 
VALUES ('40', '15', null, null), 
     (null, '5', '10', null), 
     ('10', null, '11', '12')"); 

或者,如果你想使用0,而不是空,它可能會更加對你友好的應用程序(不拋空錯誤)

mysql_query("INSERT INTO mytable(`People`, `Places`, `Ideas`, `things`) 
VALUES ('40', '15', '0', '0'), 
     ('0', '5', '10', '0'), 
     ('10', '0', '11', '12')"); 
1
INSERT INTO mytable(`People`, `Places`,`Things`,`Ideas`) 
VALUES ('40', '15', null, null), 
     ('5', '10',null, null), 
     (null, null, '140','20'), 
     ('10',null,'5','13')"); 
1

您可以編寫單獨的查詢語句像THI一個單行S:

insert into table_x (collumn_x,collumn_y) values (... ; 
insert into table_x (collumn_y, collumn_z) values (... 

結構安裝聲明dinamically可能是複雜的建設,但至少是唯一的解決方案,我可以在此刻

希望弄清楚了ü這可以幫助你