0

I have two tables Broadcastlists and Contacts(foreign key of broadcastlist). I want to show broadcastlist tables all records and count of broadcastlistid in contacts table.

My Query:-

SELECT b.id, count(c.broadcastlist_id)as Recepients,b.name 
from Broadcastlists b 
LEFT JOIN Contacts c ON b.id = c.broadcastlist_id 
group by c.broadcastlist_id;

Broadcastlists:

Id Name
1 Test 1
2 Test 2
3 Test 4
4 Test 5

Contacts:

Id Name Broadcastlist_id
1 Rahul 2
2 Mansi 1
3 Nisha 2
4 Nidhi 2
5 Prashant 1

I want Output like this

Id Name Recepients(count)
1 Test 1 2
2 Test 2 3
3 Test 3 0
4 Test 4 0

But, Output come like this, shows only one null record from left table I want all null data from left table

Id Name Recepients(count)
1 Test 1 2
2 Test 2 3
3 Test 3 0
Himanshu
  • 31,810
  • 31
  • 111
  • 133
  • Why do you group by the same column you want to count? – HoneyBadger Jun 16 '22 at 11:41
  • Broadcastlists ID 3 & 4 have name as 'Test 4' & 'Test 5' respectively however, in your desired output the name changes to 'Test 5' & 'Test 4'. Is it just mistake? – Himanshu Jun 16 '22 at 11:45

1 Answers1

0

You have grouped with a wrong column. Try this:

SELECT b.id, b.name, COUNT(c.broadcastlist_id) AS Recepients 
FROM Broadcastlists b 
LEFT JOIN Contacts c ON b.id = c.broadcastlist_id 
GROUP BY b.id, b.name;

Output

id name Recepients
1 Test 1 2
2 Test 2 3
3 Test 4 0
4 Test 5 0

See this db<>fiddle.

Himanshu
  • 31,810
  • 31
  • 111
  • 133