将null更新为值并插入另一个表

时间:2018-01-11 10:43:16

标签: php mysql

我的php脚本有问题。我必须将值从一个表插入另一个表。两个表:观察和意见都有列名user_id。问题是在观察表中,user_id列的某些行为null,并且在意见表列中,user_id设置为not null。我想将表观察中的所有值插入到实际具有值的表意见中,如果不是我想将null更改为某个值,然后插入意见表中。

这是我插入值的代码,但user_id值在每一行设置为99999:

$user = mysqli_query("SELECT user_id FROM observation;");

if ($user == NULL){
    $user = 99999;
}

$query = "INSERT INTO opinion(id, created_at, user_id, rating, updated_at, answer, description) 
    SELECT id, dateCreated, (". $user ."), grade, dateModerated, companyReply, note
    FROM observation
    ON DUPLICATE KEY UPDATE id=observation.id, created_at=observation.dateCreated, user_id=". $user .", description=observation.note, rating=observation.grade, updated_at=observation.dateModerated, answer=observation.companyReply;";
mysqli_query($db, $query) or die('Error querying database.');

1 个答案:

答案 0 :(得分:0)

您必须先获取查询结果:

$result = mysqli_query($db,"SELECT user_id FROM observation;");
$row = mysqli_fetch_assoc();

if ($row['user_id'] == NULL){
    $user = 99999;
}else{
    $user = $row['user_id'];
}