一个查询可插入包含多列的多行


One query to insert multiple rows with multiple columns

假设我想插入这个数据:

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'

我似乎在其他任何地方都找不到这样的问题。

留下你不想填满的列null

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

或者,如果您想使用 0 而不是 null,它可能对您的应用程序更友好(不会引发 null 错误)

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

您可以在一行中编写单独的查询语句,如下所示:

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

等等

动态

地挂载语句的结构可能很难构建,但至少是我目前能为您找到的唯一解决方案

希望这对你有帮助