首先,这是我正在尝试做的 SqlFiddle:http ://sqlfiddle.com/#!2/a3f19/1
所以我有两张桌子domains
和links
. 每个链接都有一个域,每个域可以有多个链接。我试图计算具有相同 IP 地址(AS count
)的域的数量,然后计算它们的 url_counts 的总和(AS total
)。这就是我想要做的事情:
我有两个数据库表
CREATE TABLE IF NOT EXISTS `domains` (
`id` int(15) unsigned NOT NULL AUTO_INCREMENT,
`tablekey_id` int(15) unsigned NOT NULL,
`domain_name` varchar(300) NOT NULL,
`ip_address` varchar(20) DEFAULT NULL,
`url_count` int(6) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=innodb DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `links` (
`id` int(15) unsigned NOT NULL AUTO_INCREMENT,
`tablekey_id` int(15) unsigned NOT NULL,
`domain_id` int(15) unsigned NOT NULL,
`page_href` varchar(750) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=innodb DEFAULT CHARSET=utf8;
以下是这些表的一些数据:
INSERT INTO `domains`
(`id`, `tablekey_id`, `domain_name`, `ip_address`, `url_count`)
VALUES
('1', '4', 'meow.com', '012.345.678.9', '2'),
('2', '4', 'woof.com', '912.345.678.010','3'),
('3', '4', 'hound.com', '912.345.678.010','1');
INSERT INTO `links`
(`id`, `tablekey_id`, `domain_id`, `page_href`)
VALUES
('1', '4', '1', 'http://prr.meow.com/page1.php'),
('2', '4', '1', 'http://cat.meow.com/folder/page11.php'),
('3', '4', '2', 'http://dog.woof.com/article/page1.php'),
('4', '4', '2', 'http://dog.woof.com/'),
('5', '4', '2', 'http://bark.woof.com/blog/'),
('6', '4', '3', 'http://hound.com/foxhunting/');
我想要得到的结果是:
012.345.678.9 1 2
912.345.678.010 2 4
但我得到的结果是
012.345.678.9 2 4
912.345.678.010 4 10
这是我的查询:
SELECT
ip_address,
COUNT(1) AS count,
SUM(url_count) AS total
FROM `domains` AS domain
JOIN `links` AS link ON link.domain_id = domain.id
WHERE domain.tablekey_id = 4
AND ip_address > ''
GROUP BY ip_address
提前谢谢我整天都在做这个:(