Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Conditional actions

Status
Not open for further replies.

hessodreamy

Programmer
Feb 28, 2005
59
GB
I need to keep a running count of actions for particular dates, so I need to say 'if this date & value aren't in the table, insert them. if they are, increment them'. Is this possible to do in 1 query? I can't figure how.

Here's what I'm doing at the minute:
Code:
SELECT count(*) FROM tracking WHERE date = current_date() AND source = 'somesource' AND target = 'sometarget'
if the result is 0, then insert it:
Code:
INSERT INTO tracking (`source`,`target`, `hits`, `date`) 
VALUES ('somesource', 'sometarget', 1, current_date())
otherwise increment:
Code:
UPDATE tracking set hits = hits + 1 WHERE `source` = 'somesource' AND `target`='sometarget' AND date = current_date()

This seems pretty inefficient to me. Can it be done in one query? btw i'm using version 4.0
 
That's the trick. I made a unique key out of concatenating other fields, then used the following:

Code:
INSERT INTO tracking VALUES(concat(substring('somesource',1,15),'_',substring('sometarget',1,15),'_',substring(current_date(),1,10)), 'somesource','sometarget',1, current_date()) ON DUPLICATE KEY UPDATE hits = hits + 1

DIdn't think OK DUPLICATE KEY was available in the version I Was running, but there you go.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top