开发者

Inserting multiple values into the same column name + overwriting/update existing entries?

This is a 2 part question which is pretty related, hence why I combined it into one:

Part 1

I have the arrays $country and $redirect each with up to 3 different values (a sum of six between them).

I however, only have two columns in my table, country and redirect. I would like to use an insert query that would insert $country[0], $country[1], etc into the column country and the same for $redirect[0], $redirect[1], etc with the column redirect.

This might be a stupid question, but would this INSERT query work, simply looping values to columns?

INSERT INTO table_name (country, redirect) values ('$country[0]', '$redirect[0]', '$country[1]', '$redirect[1]', '$country[2]', '$redirect[2]')

If not, how co开发者_运维问答uld I get this to work? I could use a for loop, but I'm concerned about the resource usage.


Part 2

How do I overwrite/update a row, where the value of column country already exists.

For example, Great Britain already exists within the column country with http://en-gb in the same row but within the column redirect.

I have an INSERT query such as INSERT INTO table_name (country, redirect) VALUES ('Great Britain', 'http://uk'), and I'd like to overwrite/update the row where Great Britain already exists within column country with the new redirect value.

Any answers/comments would be very, very, very much appreciated :)!!


To your first question, do it like this and it will work:

INSERT INTO table_name (country, redirect) 
VALUES ('$country[0]', '$redirect[0]'), 
       ('$country[1]', '$redirect[1]'), 
       ('$country[2]', '$redirect[2]')

To your second question: You need a unique index on country and then can use INSERT ON DUPLICATE KEY UPDATE:

INSERT INTO table_name (country, redirect) VALUES ('Great Britain', 'http://uk')
  ON DUPLICATE KEY UPDATE redirect='http://uk';

Or with multiple values:

INSERT INTO table_name (country, redirect) 
VALUES ('$country[0]', '$redirect[0]'), 
       ('$country[1]', '$redirect[1]'), 
       ('$country[2]', '$redirect[2]')
ON DUPLICATE KEY UPDATE redirect=VALUES(redirect)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜