We help IT Professionals succeed at work.

Table Joins - recordcount from 2nd Table (mySQL)

Maxafi
Maxafi asked
on
Joins are something I've never been able to get my head around, and this one in particular I'm really struggling with.

I have 2 tables - merchants and promotions.  I need to list all merchants, then look for the number of promotions offered by each.  Some merchants may not have any at all (in which case the value returned should be 0).

This is the code I currently have;

SELECT r.retailer_name, r.id, d.merchant_id, count(d.merchant_id) as d_cnt
FROM merchants r
LEFT JOIN promotions d
ON d.merchant_id=r.id
WHERE r.retailer_name LIKE 'A%'
ORDER BY r.retailer_name ASC

So, the end result is that I want the Merchant Name, and a count of the number of promotions alongside.  I feel as though the above code is reasonably close, but I'm getting the following error;

'Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause'

I've tried a few things, but no success.

Help would be much appreciated!
Comment
Watch Question

Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009
Commented:
try this:
SELECT r.retailer_name, r.id, count(d.merchant_id) as d_cnt
FROM merchants r
LEFT JOIN promotions d
  ON d.merchant_id=r.id
WHERE r.retailer_name LIKE 'A%'
GROUP BY r.id, r.retailer_name
ORDER BY r.retailer_name ASC

Open in new window

Author

Commented:
That did the job perfectly, thankyou!

I really appreciate the swift response too, a real lifesaver!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.