Check Data in MySQL row before Insert or Update
I would like to be able to check the data held in a row and then either insert or append if BOTH values exist to an already existing value, how can I do this?
The values I would like to check are Lat and Lon and both would be checked, if they are the same as the sent data then the Description is appended otherwise add a new row:
Table Layout e.g.:
ID(Unique) | Lat | Lon | Description | Date
1 0.1 0.1 Test some date
Data being sent:
Lat: 0.1, Lon: 0.1, Description: Test2
I would therefore like the table to end up like this:
ID(Unique) | Lat | Lon | Description | Date
1 0.1 0.1 **Test, Test2** some date
More data being sent:
Lat: 0.2, Lon: 0.1, Description: Test3
After:
ID(Unique) | Lat | Lon |开发者_StackOverflow社区 Description | Date
1 0.1 0.1 Test, Test2 some date
2 0.2 0.1 Test3 some date
I have been looking at UPDATE but I cant seem to get the correct syntax:
If you set Lat and Lon as a compound unique key you can use INSERT...ON DUPLICATE KEY UPDATE syntax.
INSERT INTO tableName (Lat, Lon, Description, Date) VALUES
(0.1, 0.1, 'Test 2', NOW())
ON DUPLICATE KEY UPDATE
Description = CONCAT(Description, ', Test2')
This has the disadvantage of being non-ANSI (and therefore not portable) SQL.
Rarely is what you're trying to do the correct answer. Normalization is.
Typically you'd create a relation table that looked like:
ID | Description(unique)
And store all the descriptions there.
Take a look at this
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
and use concat() function to append text.
精彩评论