对于不是主键的多个值的重复键更新

时间:2016-10-28 22:06:58

标签: php mysql sql

我需要基本上做一个“插入,如果不存在其他更新”类型的查询,我读过的所有内容告诉我的方式是Insert into...On Duplicate Key Update。问题是,我的主键是一个自动增量值,我从不与之交互或跟踪,我无法真正动态生成它以放入我的查询。

典型的行是:

ID| Project_ID | Location | Cost_Center_Category | Name | Number | Year | Q_1 |

1 | 200 | NUH | 1 |asfoi | 1098123|etc.

基本上每行的唯一性(不是字面意思)都带有Project_ID,Location,Cost_Center_Category,Name,Number和year的组合。如果这些都相同,则会发生Q_1的更新。

UPDATE Labour_Planning 
        SET $Q = $submit
        WHERE Project_ID = $selected_project 
        AND Year = $selected_year 
        AND Cost_Center_Category = $CCC 
        AND Cost_Center_Name = '$CC' 
        AND Cost_Center_Number = '$CC_Number'
        AND Location = '$location';

是的,我知道,SQL注入等等,我会做得更好。现在,如果上面的任何列都不同,我需要找出一种基本上插入行的方法。是否可以使用Insert into .... On Duplicate键?

我看到的每个例子都在其insert语句中使用了主键,在这种情况下这是不可能的。

2 个答案:

答案 0 :(得分:0)

我做了一些测试,这就是我得到的东西

create table test.a (
  a int PRIMARY KEY,
  b int,
  c int
);

create UNIQUE index some_index on test.a(b,c);

insert into test.a VALUES (1,2,3); 
insert into test.a VALUES (2,2,3); -- fails
insert into test.a VALUES (2,2,3) ON DUPLICATE KEY UPDATE a = 2; -- updates

因此,您只需要在您认为必须唯一的字段上创建复合唯一索引。

答案 1 :(得分:0)

我不想因为担心讨厌的开销而这样做,但考虑到我一次不会有很多更新/插入,我就是这样做的。

    $labour_select = "SELECT Project_ID 
                    FROM Labour_Planning 
                    WHERE Project_ID = $selected_project
                    AND Year = $selected_year 
                    AND Cost_Center_Category = $CCC 
                    AND Cost_Center_Name = '$CC' 
                    AND Cost_Center_Number = '$CC_Number'
                    AND Location = '$location';";
    $result = $mysqli->query($labour_select);
    $num_rows = mysqli_num_rows($result);
    if ($num_rows == 0){
        $labour_insert = "INSERT INTO Labour_Planning (Project_ID, Location, Cost_Center_Category, Cost_Center_Name, Cost_Center_Number, Year, $Q) VALUES ($selected_project, '$location', $CCC, '$CC', '$CC_Number', $selected_year, $submit)";
        $insert_result = $mysqli->query($labour_insert);
    }
    else {
        $labour_update = "UPDATE Labour_Planning 
        SET $Q = $submit
        WHERE Project_ID = $selected_project 
        AND Year = $selected_year 
        AND Cost_Center_Category = $CCC 
        AND Cost_Center_Name = '$CC' 
        AND Cost_Center_Number = '$CC_Number'
        AND Location = '$location';";
        $update_result = $mysqli->query($labour_update);
    }

现在查看准备好的陈述!我听说他们不仅保护你免受sql注入,它还会使这种性质更快!谢谢你的帮助!