G
G
giggigi2012-03-23 13:55:15
MySQL
giggigi, 2012-03-23 13:55:15

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`

(I changed the names of the fields, this may not be a completely correct request, but the essence should be clear)
After which rcnt and fcnt have the same value for some unknown reason.
Does anyone know why this is and how to avoid it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Ogra, 2012-03-23
@gigigi

Try COUNT(DISTINCT r.id).

W
wartur, 2012-03-23
@wartur

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.

I
igofed, 2012-03-23
@igofed

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 question

Ask a Question

731 491 924 answers to any question