gpt4 book ai didi

mysql - SQL 查询计算的数据多于现有数据

转载 作者:行者123 更新时间:2023-11-29 12:18:12 27 4
gpt4 key购买 nike

我想使用以下 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')

如何解决这个问题?

最佳答案

使用COUNT(DISTINCT id_visitor),这样您就不会针对访问者访问的每个文件单独计算访问者的数量。并摆脱GROUP BY vd.id_visitor

COUNT(DISTINCT data_country) 为 1,因为您已将其限制为仅限一个国家/地区(瑞典)。

关于mysql - SQL 查询计算的数据多于现有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29425708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com