`count` of subqueries
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 t开发者_StackOverflow社区his 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 are not grouping by l.listing_id
.
Also, it makes little sense to LEFT JOIN and then filter out empty rows on the right table. You can simply INNER JOIN
unless I'm missing something
SELECT l.listing_id, COUNT(e.enquiry_id) AS num_enquiries
FROM listings AS l JOIN enquiries AS e ON l.listing_id = e.enquiry_itemid AND e.enquiry_itemtype='listing' AND enquiry_datesent >= '2011-01-1 0:01' AND enquiry_datesent <= '2011-12-31 23:59'
GROUP BY l.listing_id
ORDER BY listing_title_e
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
精彩评论