Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to find the minimum number of entries linked from one table to another

Let's say I have some Table_A:

A_id | A_val
1      a
2      b
3      c

Some Table_B:

B_id | B_val
1      d
2      e
3      g

and a linker Table_C:

A_id | B_id
1      1
2      1
2      2
3      1
3      2
3      3

I'm in need of help trying to find the items in Table A that has the fewest items in Table B linked to it. I'm currently a beginner with SQL using PostgreSQL and figured it may have something to do with using a sub-query. I've managed to count the links using:

SELECT A_id, COUNT(B_id) as Num_links
  FROM TABLE_C
  GROUP BY A_id;

But I've no idea where to go from here.

like image 892
sounami Avatar asked Feb 06 '13 21:02

sounami


People also ask

How do you find the minimum value in SQL query?

The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.

How do I select a row with minimum value in SQL?

To select data where a field has min value, you can use aggregate function min(). The syntax is as follows. SELECT *FROM yourTableName WHERE yourColumnName=(SELECT MIN(yourColumnName) FROM yourTableName); To understand the above syntax, let us create a table.

Which statement is used to count the number of rows in SQL?

You can use the SQL SELECT statement with the COUNT() function to select and display the count of rows in a table of a database.


1 Answers

You could use a with clause to give an alias to your "count" query and treat it like a temp table. Then select the a_id with the num_links less-than-or-equal-to the lowest count in num_links.

WITH link_counts AS (
         SELECT a_id, COUNT(b_id) as num_links
           FROM table_c
       GROUP BY a_id
     )
SELECT a_id
  FROM link_counts
 WHERE num_links <= (SELECT MIN(num_links) FROM link_counts)

Note that this could return multiple rows if different a_id have same (lowest) number of links (for instance if a_id 1 and 4 both only had 1 link each).

like image 51
matts Avatar answered Sep 30 '22 15:09

matts