MySQL从连接表中选择两个计数

时间:2013-05-30 19:06:25

标签: mysql join

首先,这是我正在尝试做的一个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

先谢谢,我一整天都在努力:(

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

以下总结了加入前的link表:

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,但您可能也会发现它很有用。