MySQL:LEFT JOIN 和 COUNT

MySQL: LEFT JOIN and COUNT

我正在使用此查询获取所有位置:

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

现在我想在 table 'events' 的位置信息旁边显示现有事件的数量。

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

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

知道如何解决这个问题吗?

您似乎理解了根本问题:使用 left join。剩下的只是 group bycount():

的正确使用
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;

你可以试试这个:

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