Tuesday, 6 August 2013

Joining tables is giving incorrect COUNT(*) values

Joining tables is giving incorrect COUNT(*) values

For the longest time I couldn't figure out why an incorrect COUNT(*)
values were being returned. After incrementally removing parts of my query
I finally realized that joining tables were the reason behind the
incorrect values.
This is the query I'm working with:
SELECT `profiles`.`logo` AS logo,
`companies`.`company_name`,
`companies`.`url_slug`,
count(*)
FROM (`companies`)
JOIN `users` ON `users`.`id` = `companies`.`user_id`
JOIN `categories` ON `categories`.`company_id` = `companies`.`id`
JOIN `products` ON `categories`.`company_id` = `companies`.`id`
JOIN `profiles` ON `profiles`.`company_id` = `companies`.`id`
WHERE `companies`.`company_type` = 'co_type_2'
AND `companies`.`active` = 1
AND `users`.`last_login` IS NOT NULL
AND `categories`.`category_id` = '3'
AND `products`.`active` = 1
AND `products`.`xmp_1` = 1
AND `products`.`xmp_2` = 1
AND `profiles`.`field_a` = 1
GROUP BY `companies`.`id`
ORDER BY RAND(7)
Running this in my SQL program returns 28 rows, but the COUNT(*) row
returns something like 1400. I'm not sure where to head from here. I need
a column returned that returns the 28 instead of 1400.
SQL Fiddle coming in a few minutes.

No comments:

Post a Comment