join - MySQL - Correct approach event counting -


i want list users have particular event count i'm confused on approach take.

this database table:

create table `event` (   `event_id` int(11) unsigned not null auto_increment,   `visitor_id` int(11) default null,   `key` varchar(200) default null,   `value` text,   `label` varchar(200) default '',   `datetime` datetime default null,   primary key (`event_id`) ) engine=innodb auto_increment=6 default charset=utf8;   insert `event` (`event_id`, `visitor_id`, `key`, `value`, `label`, `datetime`) values     (1, 1, 'login', null, '', null),     (2, 2, 'login', null, '', null),     (3, 1, 'view_page', 'hotel', '', null),     (4, 2, 'view_page', 'hotel', '', null),     (5, 1, 'purchase_hotel', null, '', null);  create table `visitor` (   `visitor_id` int(11) unsigned not null auto_increment,   `datetime` datetime default null,   primary key (`visitor_id`) ) engine=innodb auto_increment=6 default charset=utf8;  insert `visitor` (`visitor_id`, `datetime`) values     (1, null),     (2, null); 

and approach:

select distinct     t1.`visitor_id`     `visitor` t1  join `event` t2 on t1.visitor_id = t2.visitor_id , t2.`key` = 'login' join `event` t3 on t1.visitor_id = t3.visitor_id , t3.`key` = 'view_page' , t3.`value` = 'hotel' ( select count(*) `event` `event`.`key` = 'purchase_hotel' ) > 0 

this should list visitor 1 list visitor 2 not have purchase_hotel event.

as can imagine, there more "rules" join events each particular case. can correct , improve somehow?

bonus: name of approach?

i think "set-within-sets" query. using aggregation having clause type of query. following checks 3 conditions looking for:

select visitor_id event e group visitor_id having sum(e.key = 'login') > 0 ,        sum(e.key = 'view_page' , e.value = 'hotel') > 0 ,        sum(e.key = 'purchase_hotel') > 0; 

the first condition in having clause counts number of login records , true when @ least 1 found. (if want one, change > 0 = 0.)

the second condition checks viewing of hotel page.

the third counts number of hotel purchases.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -