Author Topic: using a count when using 2 tables  (Read 257 times)

0 Members and 1 Guest are viewing this topic.

Offline BoxTopic starter

  • Irregular
  • Posts: 17
    • View Profile
using a count when using 2 tables
« on: March 02, 2010, 05:01:05 PM »
Not really sure on how to do this as i'm not too great with mysql.

I have 2 tables categories and news.
news has a unique id and a category id
categories has the catagory id and the name to be used on it.

Im trying to make some stats that lists all the category names and the number of times it has been used in the news table

This is my latest attempt at it.

Code: [Select]
SELECT COUNT( * ) AS rows, news.category, categories.catname FROM news, categories GROUP BY category ORDER BY category WHERE catid=category

Offline Dennis1986

  • Enthusiast
  • Posts: 78
  • Gender: Male
  • PHP for life!
    • View Profile
    • DennisRasmussen.dk
Re: using a count when using 2 tables
« Reply #1 on: March 02, 2010, 05:14:31 PM »
SELECT c.*, COUNT(n.category) AS newsCount FROM categories AS c LEFT JOIN news AS n ON (n.category c.idORDER BY c.catname ASC

Something like that.
It's a bit confusing to create it for you since I don't know the fields and they seem quite similar to eachother ;)
Just ask and I'll answer your question(s)! ;)

Offline BoxTopic starter

  • Irregular
  • Posts: 17
    • View Profile
Re: using a count when using 2 tables
« Reply #2 on: March 02, 2010, 05:29:57 PM »
fantastic!

I've managed to get it right thanks to your code which wasnt too far off what I needed. just had to add in the group by and change the id to catid

the working code being:
Code: [Select]
SELECT c.*, COUNT(n.category) AS newsCount FROM categories AS c LEFT JOIN news AS n ON (n.category = c.catid) GROUP BY c.catname ORDER BY c.catname ASC