计数视图(关系数据库)

时间:2013-11-29 19:36:41

标签: php mysql

table event_views

ID + EVENT_ID + VIEW_DATE + MEMBER_ID

table member_city_access

ID + MEMBER_ID + CITY_ID + PRIMARY(not PK) + VIEWING

表城市

ID + TITLE

我正在尝试从特定城市的成员获取活动的观看次数。

这就是我所拥有的

SELECT COUNT(`event_views`.`id`) c FROM `event_views`
    LEFT JOIN `member_city_access` city ON city.`member_id` = `event_views`.`member_id`
    LEFT JOIN `cities` on cities.id = city.city_id WHERE (city.city_id = '92' AND city.`primary` = 'on')
    AND `event_views`.`view_date` >= '20131103'
    AND `event_views`.`view_date` < '20131110'

我想知道我是否使用正确的“JOINS”作为计数,因为数字与事件不对齐,因此在我的报告中显示(对于1个城市)

EVENTS ADDED = 0 , EVENTS VIEWED = 3

1 个答案:

答案 0 :(得分:0)

该查询返回与where子句匹配的所有视图。如果您想按事件分隔它们,则必须按事件分组:

SELECT `event_views`.`id`,COUNT(`event_views`.`id`) c
FROM `event_views`
LEFT JOIN `member_city_access` city 
     ON city.`member_id` = `event_views`.`member_id`
LEFT JOIN `cities` 
     ON cities.id = city.city_id
WHERE city.city_id = '92'
    AND city.`primary` = 'on'
    AND `event_views`.`view_date` >= '20131103'
    AND `event_views`.`view_date` < '20131110'
GROUP BY `event_views`.`id`