[英]MySQL select two counts from Joined tables
首先,這是我要執行的操作的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
預先感謝,我整天都在努力:(
請問以下工作?
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
以下總結了link
之前的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
,但您可能還會發現它有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.