adding a new row when particular combination is not available, otherwise update a field
I have table with following structure
id int auto increment, primary key
uid int (comment: userid)
cdt date/time (comment: current date)
hits 开发者_运维百科 int (comment: no. of hits)
Now, I need a query such as
for a particular combination of 'uid' and 'cdt', if there is row available, then update hits (ie., add 1 to hits) otherwise add new row with 'uid' and 'cdt' values, and hits set to 1
Let me clear further with example
say uid = 01, and cdt = 2010-01-01, if this combination of uid and cdt is not available in table, then new row should be inserted, otherwise value of hits should be update
How to achieve this?
You could do this in two steps:
First:
Query db to know if that particular record is present:
SELECT id FROM your_table
WHERE uid = your_user_id AND cdt = your_date
Second:
If previous query returns zero rows:
INSERT INTO your_table
(uid, cdt, hits)
SELECT your_user_id, your_date, 1
else:
UPDATE your_table
SET hits = hits + 1
WHERE uid = your_user_id AND cdt = your_date
精彩评论