Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting column from one table and count from another

t1

id | name | include
-------------------
1  | foo  |  true
2  | bar  |  true
3  | bum  |  false

t2

id | some | table_1_id
-------------------------
1  | 42   |     1
2  | 43   |     1
3  | 42   |     2
4  | 44   |     1
5  | 44   |     3

Desired output:

name | count(some)
------------------
foo  | 3
bar  | 1

What I have currently from looking through other solutions here:

    SELECT      a.name, 
            COUNT(r.some)

FROM        t1 a
JOIN  t2 r on a.id=r.table_1_id
WHERE       a.include = 'true' 

GROUP BY    a.id,
            r.some;

but that seems to get me

name | count(r.some)
--------------------
foo  | 1
foo  | 1
bar  | 1
foo  | 1

I'm no sql expert (I can do simple queries) so I'm googling around as well but finding most of the solutions I find give me this result. I'm probably missing something really easy.

like image 695
Th3sandm4n Avatar asked Feb 13 '26 15:02

Th3sandm4n


2 Answers

Just remove the second column from the group by clause

SELECT      a.name, 
            COUNT(r.some)    
FROM        t1 a
JOIN  t2 r on a.id=r.table_1_id
WHERE       a.include = 'true' 
GROUP BY    a.name

Columns you want to use in an aggregate function like sum() or count() must be left out of the group by clause. Only put the columns in there you want to be unique outputted.

like image 55
juergen d Avatar answered Feb 16 '26 06:02

juergen d


This is because multiple column group requires the all column values to be same.

See this link for more info., Using group by on multiple columns

Actually in you case., if some are equal, table_1_id is not equal (And Vice versa). so grouping cannot occur. So all are displayed individually.

If the entries are like,

id | some | table_1_id
-------------------------
1  | 42   |     1
2  | 43   |     1
3  | 42   |     2
4  | 42   |     1

Then the output would have been.,

name | count
------------------
foo  | 2     (for 42)
foo  | 1     (for 43)
bar  | 1     (for 42)

Actually, if you want to group on 1 column as Juergen said, you could remove r.some; from groupby clause.

like image 36
Muthu Ganapathy Nathan Avatar answered Feb 16 '26 06:02

Muthu Ganapathy Nathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!