Reputation: 3063
So I have a query where I select from the 'sites' table, and count the number of 'pages' using a foreign key
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
I want to add another foreign key to count, possibly more than one, so I tried the below
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
The count for both numpages and numlinks are the same, and they seem to have multiplied all the tables results and is giving me some huge number that is incorrect
Any ideas?
Upvotes: 2
Views: 2614
Reputation: 389
Got the same error: "Unknown column" of the table of outer query inside the inner query and solved in different way:
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
It may be somehow slow, but works.
Upvotes: 1
Reputation: 134581
You should consider using sub-selects instead of JOIN and 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
Upvotes: 4