Reputation: 4089
First of all here's a SqlFiddle for what I'm trying to do: http://sqlfiddle.com/#!2/a3f19/1
So I have two tables domains
and links
. Every link has a domain, each domain can have multiple links. Im trying to get a count of the number of domains with the same ip address (AS count
) and then the sum of their url_counts (AS total
). Here's what Im trying to do:
I have two database tables
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;
Heres some data for those tables:
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/');
The results I want to get are:
012.345.678.9 1 2
912.345.678.010 2 4
But the results Im getting are
012.345.678.9 2 4
912.345.678.010 4 10
Heres the query I have:
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
Thanks in advance I've been working on this all day :(
Upvotes: 0
Views: 380
Reputation: 1270873
The following summarizes the link
table before the 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;
It doesn't use lcnt
, but you might also find that useful.
Upvotes: 1
Reputation: 3135
Will the following work?
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
Upvotes: 2