MySQL计算多个外键

时间:2011-01-11 15:59:47

标签: mysql count foreign-keys

所以我有一个查询,我从'sites'表中选择,并使用外键计算'pages'的数量

SELECT s_id, s_name, s_main_url, COUNT(p_id) AS numpages
FROM sites
INNER JOIN pages ON sites.s_id = pages.site_id
GROUP BY pages.site_id
ORDER BY s_id ASC

我想添加另一个外键来计数,可能不止一个,所以我尝试了下面的

SELECT s_id, s_name, s_main_url, COUNT(p_id) AS numpages, COUNT(l_id) AS numlinks
FROM sites
INNER JOIN pages ON sites.s_id = pages.site_id
INNER JOIN links ON sites.s_id = links.site_id
GROUP BY pages.site_id, links.site_id
ORDER BY s_id ASC

numpages和numlinks的计数是相同的,它们似乎使所有表结果成倍增加,并且给了我一些不正确的数字

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

您应该考虑使用子选择而不是JOIN和GROUP BY。

SELECT s_id, s_name, s_main_url, numpages, numlinks
FROM sites, 
(SELECT COUNT(p_id) as numpages FROM pages WHERE pages.site_id = sites.s_id) as cnt_pages,
(SELECT COUNT(l_id) as numlink FROM links WHERE links.site_id = sites.s_id) as cnt_links
ORDER BY s_id ASC

答案 1 :(得分:0)

得到了同样的错误:内部查询中的外部查询表的“未知列”以不同的方式解决:

SELECT s_id, s_name, s_main_url, numpages, numlinks,
(SELECT COUNT(p_id) FROM pages WHERE pages.site_id = sites.s_id) as cnt_pages,
(SELECT COUNT(l_id) FROM links WHERE links.site_id = sites.s_id) as cnt_links
FROM sites, 
ORDER BY s_id ASC

它可能有点慢,但有效。