我需要一点MySQL查询帮助。
我有两个表,一个表是backlinks
的列表,带有is_homepage
(bool)标志。第二个表是domains
的所有backlinks
,link_found
(bool)标志和url_count
列的列表,其中包含的行数与每个域关联的backlinks
表。
请注意,domain_id
列是域表id
列的外键。下面是一些样本数据。
反向链接
id domain_id is_homepage page_href
1 1 1 http://ablog.wordpress.com/
2 1 0 http://ablog.wordpress.com/contact/
3 1 0 http://ablog.wordpress.com/archives/
4 2 1 http://www.somewhere.org/
5 2 0 http://www.somewhere.org/page=3
6 3 1 http://www.great-fun-site.com/
7 3 0 http://www.great-fun-site.com/index.html
8 4 0 http://red.blgspot.com/page=7
9 4 0 http://blue.blgspot.com/page=9
结构域
id url_count link_found domain_name
1 3 1 wordpress.com
2 2 0 somewhere.org
3 2 1 great-fun-site.com
4 2 1 blgspot.com
我希望从上述数据得到的结果是: count = 2,total = 5 。
我试图从域表中获取行数(count),然后域表WHERE url_count
中link_found
(总计)的总和为1,其中一个链接在反向链接表is_homepage
中是1。
这是我正在尝试使用的查询。
SELECT SUM(1) AS count, SUM(`url_count`) total
FROM `domains` AS domain
LEFT JOIN `backlinks` AS link ON link.domain_id = domain.id
WHERE domain.id IN (
SELECT DISTINCT(bl.domain_id)
FROM `backlinks` AS bl
WHERE bl.tablekey_id = 11
AND bl.is_homepage = 1
)
AND domain.link_found = 1
AND link.is_homepage = 1
GROUP BY `domain`.`id`
此查询的问题是它为domains
表中的每个条目返回一行。我想我可能还需要一个子查询来添加返回的结果,但我不确定这是否正确。有谁看到我做错了什么?谢谢!
编辑:
我遇到的问题是,如果反向链接表中有多个主页,则会多次计数。我只需要计算一次每个域名。
答案 0 :(得分:0)
好吧,你不应该做一个小组,因为你没有选择聚合字段以外的任何东西。我不是mysql专家,但这应该有效:
SELECT count(d.id) as count, sum(d.url_count) as total from domains as d
inner join backlinks as b
on b.domain_id = d.id
Where d.Link_found = 1 and b. is_homepage = 1
答案 1 :(得分:0)
您为domains
表中的每个条目获取一行的原因是您按domain.id
分组。如果您只想要总计,请不要使用GROUP BY
件。
我认为一个相当简单的查询可以解决这个问题:
SELECT COUNT(*), SUM(domains.URL_Count)
FROM domains
WHERE domains.link_found = 1 AND domains.id IN (
SELECT domain_id FROM backlinks WHERE is_homepage = 1)
有一个有效的SQLFiddle here。
答案 2 :(得分:0)
感谢您的帮助。对不起,我很难解释我需要一个MySQL小提琴:)
如果有人感兴趣的话,我会说:
SELECT SUM(1) AS count, SUM(total) AS total
FROM
(
SELECT SUM(`url_count`) total
FROM `domains` AS domain
LEFT JOIN `backlinks` AS link ON link.domain_id = domain.id
WHERE domain.id IN (
SELECT DISTINCT(bl.domain_id)
FROM `backlinks` AS bl
WHERE bl.tablekey_id = 11
AND bl.is_homepage = 1
)
AND domain.link_found = 1
AND link.is_homepage = 1
GROUP BY `domain`.`id`
) AS result