Skip to content
Advertisement

SQL count column from another table

I have two tables in a database

The first being people which has the columns

and another being relationships which represents a one way following

Where me and following are foreign keys that match the id primary key on the person in table people.

I want to run a query that given a id of a person returns their name and the count of people that they are following and the number who are following them.

My current attempt is

But it is throwing in error about the where syntax. I think I need to use group by somewhere but I am struggling as to how that works over multiple tables.

So say given id=2 it would return [{name: "sam", followers: 4, following: 3}]

Advertisement

Answer

This could be solved simply with inline correlated subqueries, like:

This should be a quite efficient option.

Otherwise, starting from your existing query, you can also left join and aggregate:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement