Please could someone help with what (i think) should be a fairly straight forward query, but I have been tearing my hair out for hours.
I have 2 tables, ‘listings’ and ‘enquiries’.
I want to return a set of listings alongside the number of enquiries that they have received, e.g.
Listing 1 (5 enquiries)
Listing 2 (3 enquiries)
Listing 7 (2 enquiry)
So far, I have got:
SELECT l.listing_id, COUNT(e.enquiry_id) AS num_enquiries
FROM listings AS l LEFT JOIN enquiries AS e ON l.listing_id = e.enquiry_itemid
WHERE e.enquiry_itemtype='listing' AND enquiry_datesent >= '2011-01-1 0:01' AND enquiry_datesent <= '2011-12-31 23:59'
HAVING num_enquiries > 0
ORDER BY listing_title_e
But this is only returning 1 Listing Row, with the total count of all enquiries, e.g.
Listing 1 (10 enquiries)
As you can see, enquiries are associated with Listings by having the itemtype ‘listing’ and itemid matching listingid.
Could anyone help me? Many thanks!
You forget Group By – so you get number of all enquiries , and why you are using left join with HAVING num_enquiries > 0 – JOIN will do same thing. And conditions to enquiries looks better in ON part