Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining sql select and Count

Tags:

sql

count

I have two tables

A and B

 A                          B
-----------------         -----------------
a_pk (int)                b_pk (int)
a_name(varchar)           a_pk (int)
                          b_name (varchar) 

I could write a query

SELECT a.a_name, b.b_name
FROM  a LEFT OUTER JOIN b ON a.a_pk = b.a_pk

and this would return me a non distinct list of everything in table a and its table b joined data. Duplicates would display for column a where different b records shared a common a_pk column value.

But what I want to do is get a full list of values from table A column a_name and ADD a column that is a COUNT of the joined values of table B.

So if a_pk = 1 and a_name = test and in table b there are 5 records that have a a_pk value of 1 my result set would be

a_name        b_count
------        -------
test           5
like image 327
Bastyon Avatar asked Dec 07 '22 12:12

Bastyon


2 Answers

The query should like this :

SELECT 
    a.a_name, 
    (
        SELECT Count(b.b_pk) 
        FROM b 
        Where b.a_pk = a.a_pk
    ) as b_count 
FROM  a
like image 123
Kundan Singh Chouhan Avatar answered Jan 04 '23 20:01

Kundan Singh Chouhan


SELECT a_name, COUNT(*) as 'b_count'
FROM 
    A a
    JOIN B b
    ON a.a_pk = b.a_pk
GROUP BY a_name
like image 34
Vikdor Avatar answered Jan 04 '23 20:01

Vikdor