One query to insert multiple rows with multiple co

2019-02-20 10:31发布

Let's say I want to insert this data:

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

I understand that this is how you'd execute the above:

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

But what if I wanted to insert into more than two columns with a single query? What if the data to be inserted was like this:

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'

I can't seem to find a question like this anywhere else.

4条回答
Viruses.
2楼-- · 2019-02-20 10:34
mysql_query("INSERT INTO mytable(`People`, `Places`, `Ideas`, `things`)
 VALUES ('40', '15',  null, null),
        (null, '5',   '10', null),
        ('10',  null, '11', '12')");

Or if you want to use 0 instead of null, it will likely be more friendly to you application (no throwing null errors)

mysql_query("INSERT INTO mytable(`People`, `Places`, `Ideas`, `things`)
 VALUES ('40', '15', '0',  '0'),
        ('0',  '5',  '10', '0'),
        ('10', '0',  '11', '12')");
查看更多
叼着烟拽天下
3楼-- · 2019-02-20 10:46

You could write separate query statements in one single line like this:

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

and so on

the structure to mount the statement dinamically may be complex to build, but at least is the only solution i can figure out for u at the moment

hope this helps you

查看更多
劫难
4楼-- · 2019-02-20 10:49
INSERT INTO mytable(`People`, `Places`,`Things`,`Ideas`) 
VALUES ('40', '15', null, null),
       ('5', '10',null, null),
       (null, null, '140','20'),
       ('10',null,'5','13')");
查看更多
Luminary・发光体
5楼-- · 2019-02-20 10:50

Leave the columns you don't wanto to fill with null

INSERT INTO mytable(`People`, `Places`, Things, Ideas) 
VALUES ('40', '15', null, null),(null, null, 100, 20)
查看更多
登录 后发表回答