Question

This is a follow up question for https://stackoverflow.com/questions/18487327/mysql-correct-approach-event-counting

This is the 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 INTO `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 INTO `visitor` (`visitor_id`, `datetime`)
VALUES
    (1, NULL),
    (2, NULL);

CREATE TABLE `attribute` (
  `attribute_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `visitor_id` int(11) DEFAULT NULL,
  `key` varchar(200) DEFAULT NULL,
  `value` text NOT NULL,
  `label` varchar(200) NOT NULL DEFAULT '',
  `datetime` datetime DEFAULT NULL,
  PRIMARY KEY (`attribute_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `attribute` (`attribute_id`, `visitor_id`, `key`, `value`, `label`, `datetime`)
VALUES
    (1, 1, 'TITLE', 'Professor', '', NULL);

I am running following query:

SELECT
    `e`.`visitor_id`
FROM 
    `event` e,
    `attribute` a
GROUP by 
    `e`.`visitor_id`
HAVING
    sum(e.key = 'LOGIN') > 0
AND sum(e.key = 'VIEW_PAGE' and e.value = 'HOTEL') > 0 
AND sum(e.key = 'PURCHASE_HOTEL') > 0
AND sum(a.key = 'TITLE' and a.value = 'Professor') > 0

and I'm expecting that only the visitor (1) with the TITLE = 'Professor' attribute should be returned but somehow the query gives me both visitors.

  • What am I doing wrong here so that both users are returned?
  • I'm attaching all conditions with "AND" shouldn't this exclude visitor 2 if his condition does not match (TITLE = 'Professor')?
Was it helpful?

Solution

You are not joining on the two tables:

SELECT
    `e`.`visitor_id`
FROM 
    `event` e join
    `attribute` a
    e.visitor_id = a.visitor_id
GROUP by 
    `e`.`visitor_id`
HAVING
    sum(e.key = 'LOGIN') > 0
AND sum(e.key = 'VIEW_PAGE' and e.value = 'HOTEL') > 0 
AND sum(e.key = 'PURCHASE_HOTEL') > 0
AND sum(a.key = 'TITLE' and a.value = 'Professor') > 0;

With the cross join (your original formulation), all attributes were on all events. So, all events matched the criteria.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top