Jump to content

mySQL join and count


WatsonN

Recommended Posts

Hello all, I have to mysql tables and I want to join them and count the amount of rows in one.

I have two tables YBK_Login and YBK_Ads, what I want to do is join them together and select a user's ID from YBK_Login and see how many entries that user has posted in YBK_Ads.

The common field from YBK_Login is ID and in YBK_Ads is UID.

Also, if you could explain so I can learn from this that would be much appreciated.

 

If you need me to be more specific please let me know.

 

 

Thank you in advanced.

Link to comment
Share on other sites

Hi

 

Something like this

 

SELECT a.UID, COUNT(b.id)
FROM YBK_Login a
LEFT OUTER JOIN YBK_Ads b
ON a.UID = b.UID
GROUP BY a.UID

 

Basically joins the 2 tables together. Uses a left join so that you will still get a row returned when there is no matching row on the ads table. Then counts the occurances of the primary key on the 2nd table (COUNT used like this will ignore nulls, so anyone with no ads will have 0 here, using COUNT(*) would count the rows and would give 1). Groups by the shared key field to get the count per occurance of that key.

 

If you want more fields from the first table then add them to both the SELECT and the GROUP BY.

 

All the best

 

Keith

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.