0

首先,这是我正在尝试做的 SqlFiddle:http ://sqlfiddle.com/#!2/a3f19/1

所以我有两张桌子domainslinks. 每个链接都有一个域,每个域可以有多个链接。我试图计算具有相同 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

提前谢谢我整天都在做这个:(

4

2 回答 2

2

下面的工作吗?

SELECT 
ip_address,
(select count(*) from domains d2 where domains.ip_address = d2.ip_address) as dcount,
count(ip_address)
from links
join domains on link.domain_id = domains.id
where domain.tablekey_id = 4
and ip_address <> ''
group by ip_address
于 2013-05-30T19:10:34.380 回答
1

下面总结link了join前的表:

SELECT ip_address,
       COUNT(1) AS count,
       SUM(url_count) AS total
FROM `domains` AS domain
JOIN (select l.domain_id, count(*) as lcnt
      from `links` l
      group by l.domain_id
     ) link
     ON link.domain_id = domain.id
WHERE domain.tablekey_id = 4 AND ip_address > '' 
GROUP BY ip_address;

它不使用lcnt,但您可能也会发现它很有用。

于 2013-05-30T19:10:40.683 回答