I’m using PHP and I need to insert a new record in a MySQL DB or if it exists simply update it. I read several answers where they propose to use REPLACE or INSERT...ON DUPLICATE KEY UPDATE, however if I well understood, these two option imply the use of unique fields or primary keys (that are unique). In my case the MySQL table has values similar to this:
Timestamp | Query1 | Query2 | Result
--------------------------------------------------------
2012-10-13 08:15:27 | American | Men | here result
2012-10-13 08:15:23 | American | Men | result2
2012-10-13 08:15:27 | American | Women | other result
2012-10-13 08:15:27 | German | Men | here result
Therefore I cannot have primary keys or univoque fields since “query1”, “query2” and “Result” can have the same values (e.g. I can have several records with more fields containing “American” (query1) and “Men” (query2) and different results.
At the moment in PHP I’m using:
INSERT INTO results (Timestamp, Query1, Query2, Result) VALUES ('$current_timestamp', '$nationality', '$gender', '')
Which just append all the records and create a huge DB. But what I want to achieve is adding a new record just if the entire combination query1&query2&result doesn’t exist. Otherwise I just want to update the “timestamp” field.
For instance if my PHP script produces the following data:
Timestamp | Query1 | Query2 | Result
2012-10-13 08:15:23 | American | Men | result2
and the database already contains this exact combination of “American”&”Men”&”result2” then just the field “timestamp” is updated. Otherwise, if the combination is different (e.g. “American” “Men” “result3) a new record is added to the table.
Thank you in advance for your help
Even absent a single
PRIMARY KEYcolumn like a typicalAUTO_INCREMENTinteger, if those three columns are meant to be a unique combination you ought to define them as a composite key . This will not only preserve uniqueness but also enforce indexing on them as a unit.You may then use
ON DUPLICATE KEY UPDATEwhen inserting to abort insertion on key violations and update the timestamp instead.Note: We assume the PHP variables have been properly escaped already.
Note 2: If the value of
$current_timestampis indeed the current timestamp and not some stored value, I recommend using MySQL’sNOW()function rather than pass in a PHP variable.Same goes for the
$current_timestampin theVALUES()list…