MySQL:LEFT JOIN和COUNT

时间:2016-02-18 00:53:26

标签: mysql left-join

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

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

现在,我想在表格' events'中显示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

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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