954,600 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

SQL statement to count foreign keys

Hi

I have two tables that I want to use to build a third. They have a many-to-one relationship for one of the columns. Table A has the "one" side of the many-to-one relationship. Table B has many rows that have foreign keys referencing Table A. I want to write a SQL statement that will return rows that tell how many references to each row in Table B are in Table A. For example:

Table A
1 A
2 B
3 C

Table B
1
1
1
2
2
2
2
3
3


I want the statement to return:
A 3
B 4
C 2

Does this make sense or is more information necessary?

Thany you in advance

trihaitran
Light Poster
28 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

How about :

SELECT COUNT (*) DISTINCT FROM TABLE_NAME;


Definetely not sure, but just give it a shot?

AdarshN
Newbie Poster
20 posts since Jul 2008
Reputation Points: 10
Solved Threads: 1
 

I found the solution.

SELECT name, COUNT(fk)
FROM TableA INNER JOIN TableB ON TableA.id = TableB.fk
GROUP BY TableB.fk
trihaitran
Light Poster
28 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You