Categories
SQL / MySQL Tips and Tutorials

MySQL: Counting Number of Records or Rows by a Foreign Column (from Another Table)

Well, MySQL doesn’t actually have anything called Foreign Key, it’s just my way of saying a alien column from another table.

Let’s say 2 tables are related, 1 is books and the other is subjects. Any book in book table falls into one of the subjects, thus having a subject column referencing the ID of one of the subjects in subject table.

You need to know the number of books from each of the subjects, namely, 243 books in subject Education, 77 books in Science, etc.

Now how do we do this? Simple. Just perform the following SQL query:

SELECT subject.id, COUNT(book.id) FROM subject, book GROUP BY book.subject HAVING book.subject = subject.id

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.

One reply on “MySQL: Counting Number of Records or Rows by a Foreign Column (from Another Table)”

Comments are closed.