简体   繁体   中英

MySQL count multiple foreign keys

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM