这是为 mysql 查询准备一个字符串。问题是关于NULL。我只希望“d”列为 NULL(如果在数据数组中设置为 null)。问题是'isset'如果为空则为假,如果未设置'is_null'也为真..
那么我该如何解决呢?
我在php中有以下内容:
<?
$data = array(
array('id' => 1, 'c' => '', 'd' => NULL, 'e' => '', 'f' => '', 'i' => 'ciao', 'j' => '', 'k' => ''),
array('id' => 2, 'b' => '', 'c' => '', 'd' => NULL, 'e' => '', 'f' => 'hello', 'g' => '', 'h' => '', 'i' => ''),
);
$col = array('id', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k');
$insert = $update = array();
foreach (array_values($data) as $key => $val){
$val_stack = array();
$insert[$key] = "(";
foreach ($col as $c){
if (isset($val[$c]) && is_null($val[$c])) $val_stack[] = 'NULL';
else if (isset($val[$c])) $val_stack[] = "'".$val[$c]."'";
else $val_stack[] = "''";
}
$insert[$key] .= implode(', ', $val_stack).")";
}
foreach (array_diff($col, array('id')) as $v){
$update[] = $v == 'd' ? "$v=COALESCE(VALUES($v), $v)" : "$v=VALUES($v)";
}
echo "INSERT INTO table (".implode(', ', $col).") VALUES ".implode(', ', $insert)." ON DUPLICATE KEY UPDATE ".implode(', ', $update);
?>
这个输出:
INSERT INTO table (id, b, c, d, e, f, g, h, i, j, k) VALUES ('1', '', '', '', '', '', '', '', 'ciao', '', ''), ('2', '', '', '', '', '你好', '', '', '', '', '')重复键更新 b=VALUES(b), c=VALUES(c), d=COALESCE(VALUES(d), d), e=VALUES(e), f=VALUES(f), g=VALUES(g) , h=值(h), i=值(i), j=值(j), k=值(k)
如果我在内部“foreach”(if (/* isset($val[$c]) && */is_null($val[$c]))
)中评论“isset”,它会输出:
插入表(id,b,c,d,e,f,g,h,i,j,k)值('1', NULL,'',NULL,'','',NULL,NULL,' ciao', '', ''), ('2', '', '', NULL , '', 'hello', '', '', '', NULL, NULL ) ON DUPLICATE KEY UPDATE b=VALUES (b), c=值(c), d=合并(值(d), d), e=值(e), f=值(f), g=值(g), h=值(h) , i=值(i), j=值(j), k=值(k)
我想要的输出:
INSERT INTO table (id, b, c, d, e, f, g, h, i, j, k) VALUES ('1', '', '', NULL , '', '', '', ' ', 'ciao', '', ''), ('2', '', '', NULL , '', 'hello', '', '', '', '', '') 重复关键更新 b=VALUES(b), c=VALUES(c), d=COALESCE(VALUES(d), d), e=VALUES(e), f=VALUES(f), g=VALUES(g), h =VALUES(h), i=VALUES(i), j=VALUES(j), k=VALUES(k)