2016-10-28 98 views
1

我需要基本上做一個「插入如果不存在其他更新」類型的查詢,並且我讀取的所有內容告訴我去的方式是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,地點,Cost_Center_Category,姓名,號碼和年。如果全部相同,則會發生更新至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注入和所有這一切,我會做得更好。現在,我需要找出一種方法來基本上插入一行,如果任何上述列不同。這是可能的插入....在重複鍵?

我看到的每個示例都在插入語句中使用主鍵,在這種情況下這不是真的可行。

+0

是的,它是可以用一個獨特的密鑰,但在我看來,你會更好地重組爲兩個表 – andrewtweber

+0

'一式兩份'會觸發任何「唯一鍵」違規。它不僅僅是主鍵。 –

回答

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注入的攻擊,還可以使這種情況更快!感謝所有的幫助!

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 

因此,所有你需要的是創建您認爲必須是唯一的字段組合唯一指標。

+0

這將工作的MySQL數據庫? –