tags:

views:

195

answers:

3

How would i go about counting the number of rows that match two variables?

I have a table called: users

and fields called: username & referral

I have another table called: comments

and fields called: *comment_username*

This is the situation, I need to fetch the number of referrals with at least 10 comments (rows in the comments' table) that a specific user has referred.

So i was thinking the code should be something like this crude outline.

    $username = 'bob';
$validrefferalcount = 0;
function validreferrals($username){

    $referreduser = SQL select * from users where referral='$username';

    foreach ($referreduser)   {

    $numberofcomments = SQL count * from comments where comment_username ='$referreduser';
if ($numberofcomments >= 10){
$validreferralcount = $validreferralcount + 1;
}

    }
return $validreferralcount;
    }

I apologize for the bad syntax, etc...

Thanks for reading.

+2  A: 

You should use JOIN in your case. Something like (if I understand correctly)

SELECT count(*) FROM users 
   RIGHT JOIN comments ON comments.comment_username = users.username 
   WHERE users.referral = '$username'

You can find more information here

Christian Toma
close enough :D, i'll fill in the rest
jiexi
+2  A: 

Since my actual post count does not allow for comments yet, some additions to christians answer.

A having clause against the count, so the >= 10 condition is matched would be a good idea

tDo
+1 and May I change my post according to your suggestion ?
Christian Toma
Sure, that's why I'd hope to post a comment on it instead of another answer ;)
tDo
unknown (google) has posted the full query already
Christian Toma
+3  A: 

What about this query :

SELECT COUNT(*) FROM (
    SELECT username, COUNT(*) AS c_comments
    FROM users
        JOIN comments ON username = comment_username
    WHERE referral = 'referral'
    GROUP BY username
) t
WHERE t.c_comments > 10;
S0pra
looks good, gotta try it first tho
jiexi
is the "t" supposed to be there in the second to last line?
jiexi
@jjexi - Yes it's supposed to be. t is the SELECT COUNT(*) FROM (*) query result
Christian Toma
Yes, it's an alias for the sub-query.
S0pra