Answer the question
In order to leave comments, you need to log in
Multiple COUNT() + JOIN = same values?
There is a selection from the database in which JOIN of two different tables is made, COUNT () is done on these two tables.
The fact is that both of these counts for some reason have exactly the same meaning.
Request example:
SELECT
`t`.`id`,`t`.`title`,
COUNT(`r`.`id`) AS `rcnt`,
COUNT(`f`.`id`) AS `fcnt`
FROM
`table` AS `t`
LEFT JOIN
`rtable` AS `r` ON `t`.`id` = `r`.`r_id`
LEFT JOIN
`ftable` AS `f` ON `f`.`w_id` = `t`.`w_id`
GROUP BY
`t`.`id`
Answer the question
In order to leave comments, you need to log in
Well, with JOIN, the rows are the same there and there, so COUNT is working correctly.
You need to make 2 subqueries separately for each table in this code section COUNT(`r`.`id`) AS `rcnt`. Well, if I understood the problem correctly.
As a result of the query, you will get only N rows. Accordingly, each COUNT will return the number N, because COUNT also takes NULL values into account.
You can change your query to:
SELECT `t`.`id`,`t`.`title`, (select COUNT(`id`) from rtable) AS `rcnt`, (select COUNT(`id`) from ftable) AS `fcnt`,
and blah blah blah
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question