我可以避免在 INSERT 查询中用 NULL 值覆盖列吗?
我的 php 页面中对同一个表有两个不同的查询,如果两列有两个不同的值,则执行第一个查询,但在某些情况下,我只能使用第一个值,我可以使用相同的查询来执行此操作吗或者我应该使用两个不同的查询?
// 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 column_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
那么我可以使用新值执行 INSERT 语句而不用空值覆盖旧值吗?
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 column_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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
INSERT
永远不会覆盖旧记录(尽管如果您尝试插入打破唯一键约束的记录,它可能会失败)。因此,即使$value_2
为 null,您也可以只使用第一个查询,并获得相同的结果。如果您想覆盖记录,则需要使用
UPDATE
语句。在这种情况下,如果您愿意,您可以只覆盖单个列。请参阅http://dev.mysql.com/doc/refman/5.0 /en/update.html 用于 UPDATE 语法。在唯一键的情况下,还有 REPLACE 来覆盖旧行,但这听起来与您想要做的相反。
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.