MySQL – Get Count of Subjects with Records in Posts Table

MySQLPHP

I have two tables: posts and subjects.

posts may have subjects, but not all subjects may have been assigned to some posts. Now I want to count only those subjects with at least one post related to them.

subject columns are: id, name
posts columns are: id, title, subject_id

Best Answer

This should be fairly simple :

select distinct subject.* from subject inner join post on subject.id = post.subject_id

To get only count :

select count(distinct subject.id) as subject_count from subject inner join post on subject.id = post.subject_id;