2016-02-18 158 views
0

我使用這個查詢來獲取所有位置:MySQL的:LEFT JOIN和COUNT

SELECT 
* 
FROM 
locations 
WHERE 
cat='Bars' 
ORDER BY 
locationname 
ASC 

現在我想顯示從表「事件」太locationinfo旁邊現有活動的量。

Table 'locations': (all unique locations) 
locationid|locationname|address|cat 

Table 'events': (different eventid's but maybe multiple hits for locationid) 
eventid|locationid|eventname|eventdate 

任何想法如何解決這個問題?

回答

1

你可以試試這個:

SELECT COUNT(e.eventid), l.locationid 
FROM locations l 
LEFT JOIN events e ON l.locationId = e.locationId 
WHERE cat='Bars' 
GROUP BY l.locationId 
ORDER BY .locationname ASC 
1

你似乎明白的根本問題:使用left join。剩下的只是group by和使用權的count()

SELECT l.*, COUNT(e.locationid) 
FROM locations l LEFT JOIN 
    events e 
    ON l.locationid = e.locationid 
WHERE l.cat = 'Bars' 
GROUP BY l.id;