开发者

Can I avoid to overwrite a column with a NULL value on INSERT query?

开发者 https://www.devze.com 2022-12-15 22:07 出处:网络
I have two different queries in my php page for the same table, the first one is executed if I have two different values for two columns, but in some case, i can use only the first value, can I do it

I have two different queries in my php page for the same table, the first one is executed if I have two different values for two columns, but in some case, i can use only the first value, can I do it with the same query or should I use two different queries?

// query 1
"INSERT INTO my_table (column_1, column_2) VALUES ('$value_1', '$value_2')";

// second query, used if $value_2 is null
"INSERT INTO my_table (column_1) VALUES ('$value_1')";

// can I do something like this without use a SELECT for col开发者_StackOverflowumn_2 before the INSERT?
$value_2 = null;
"INSERT INTO my_table (column_1, column_2) VALUES ('$value_1', '$value_2')";
// ======================================= new value === ^   |    ^ === mantain old value because it's null

so can I execute an INSERT statement with new vals without overwrite the old vals with a null value?


An INSERT will never overwrite an old record (though it could fail if you try to insert a record that breaks a unique key constraint). So you can just use the first query, even if $value_2 is null, and get the same results.

If you want to overwrite records, you will need to use an UPDATE statement. In that case you could overwrite only a single column, if you wanted to. See http://dev.mysql.com/doc/refman/5.0/en/update.html for the UPDATE syntax.

There is also REPLACE to overwrite old rows in the case of unique keys, but it sounds like this is the opposite of what you want to do.

0

精彩评论

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