我想通过使用此SQL查询来计算来自瑞典的访问者数量(基于IP地址):
SELECT COUNT(vd.data_country)
FROM visitors_details AS vd
JOIN visitors AS v
ON vd.id_visitor = v.id
WHERE v.id_website = '1'
AND vd.data_country = 'SE'
GROUP BY vd.id_visitor
此SQL查询的问题在于它显示了来自瑞典的830位访问者。当我从数据库中手动统计瑞典访客时,我会得到671名访客(我在HeidiSQL中标记了每个瑞典访客,所以我没有错误计算)。
如果我将COUNT(vd.data_country)
更改为COUNT(DISTINCT vd.data_country)
,则只会显示1位访问者。
以下是数据库的外观:
CREATE TABLE IF NOT EXISTS `visitors` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_website` int(11) NOT NULL DEFAULT '0',
`data_ipaddress` text NOT NULL,
`data_useragent` text NOT NULL,
`data_referer` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
)
CREATE TABLE IF NOT EXISTS `visitors_details` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_visitor` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`id_permissions` int(11) NOT NULL,
`data_filename` text NOT NULL,
`data_filename_get` text NOT NULL,
`data_city` text NOT NULL,
`data_postalcode` bigint(20) NOT NULL,
`data_county` text NOT NULL,
`data_country` text NOT NULL,
`data_location` text NOT NULL,
`data_hostname` text NOT NULL,
`data_organisation` text NOT NULL,
`datetime_occurred` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
)
INSERT INTO `visitors` (`id`, `id_website`, `data_ipaddress`, `data_useragent`, `data_referer`)
VALUES(1, 1, '127.0.0.1', '', '')
INSERT INTO `visitors_details` (`id`, `id_visitor`, `id_user`, `id_permissions`, `data_filename`, `data_filename_get`, `data_city`, `data_postalcode`, `data_county`, `data_country`, `data_location`, `data_hostname`, `data_organisation`, `datetime_occurred`)
VALUES(1, 1, 0, 0, 'page-start.php', '-', 'city', 12345, 'county', 'SE', 'loc', 'hostname', 'org', '2015-03-31 18:45:37')
我该如何解决这个问题?
答案 0 :(得分:1)
使用COUNT(DISTINCT id_visitor)
,这样您就不会为访问的每个文件单独计算访问者数。并摆脱GROUP BY vd.id_visitor
。
COUNT(DISTINCT data_country)
为1,因为您将其限制在一个国家/地区(瑞典)。