I have a reputation system on my site, similar to Stack Overflow, where a member will get points for doing different tasks. One of these tasks is commenting on blog articles.
I only want to give my user 5 points for writing 1 comment on an article. If they write additional comments on the same article, or reply to other comments within that article, they should still only get the first 5 points.
To do this I’ve been querying the blog_comments table first, checking to see if that member has already posted a comment on that article previously, if not, in another query, I will add the 5 points to the members_reputation table. My example below shows this:
SELECT COUNT(*) AS duplicates_found FROM blog_comments
WHERE member_id = 12722 AND article_id = 30202
// in my server-side language I would have
// if duplicates_found = 0 then
INSERT INTO members_reputation (member_id, awarded_for, awarded_when, awarded_what)
VALUES (12722, 'Posted a comment', Now(), 5)
Is there a way to shorten these two queries to make one single one? I was thinking about adding the select query to my insert query as a sub-query, but I’ll be honest, it confused me quite a lot as I’m not even sure I can use INSERT & WHERE together, can I?
Anyway, any suggestions are always gratefully received.
MY ANSWER
Thanks to Michael’s kind answer, the answer to my question is:
INSERT INTO members_reputation (member_id, awarded_for, awarded_when, awarded_what)
SELECT 12722, 'Posted a comment', Now(), 5 FROM DUAL
WHERE NOT EXISTS
(
SELECT * FROM blog_comments
WHERE member_id = 12722 AND article_id = 30202
)
Try this:
UPDATE:
@MartinG I don’t have MySQL in my box. I tried it on http://sqlzoo.net though, seems MySQL is like Oracle, SELECT with no source table requires a dummy table, you can use DUAL table in lieu of dummy table