一个查询插入多列多行(One query to insert multiple rows with

2019-06-23 21:45发布

比方说,我想插入这样的数据:

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'

我似乎无法找到这样的其他地方的问题。

Answer 1:

离开列你不wanto,以填补null

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


Answer 2:

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')");


Answer 3:

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


Answer 4:

你可以写在这样一个单行单独的查询语句:

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

等等

该结构dinamically安装声明可能是复杂的建设,但至少是唯一的解决方案,我可以在瞬间想出了ü

希望这可以帮助你



文章来源: One query to insert multiple rows with multiple columns