tags:

views:

833

answers:

3
SELECT `name` , COUNT(*) AS `count`
FROM `t1`, `t2`
WHERE `t2`.`id` = `t1`.`id`
GROUP BY `t2`.`id`

I want to obtain the name from t1 and the number of rows in t2 where the id is the same as on t1.

I've got the above so far, however it won't return any data if there are no rows in t2 that match. I'd prefer count to be 0 (or NULL) if there are no rows, and the name still returns.

Edit: I'd like to be able to sort by the count descending. (or name ASC) is that possible?

A: 

Do a union to get the other set SELECT name , COUNT(*) AS count FROM t1, t2 WHERE t2.id = t1.id GROUP BY t2.id UNION Select name, 0 as count from t1 where NOT EXISTS (select 1 from t2 where t2.id = t1.id)

Dheer
Thanks for your help. Is that the most efficient/elegant way? Is there a way to do this using JOINs?
Steve
+3  A: 

This should work for you:

SELECT `t1`.`id` , COUNT(`t2`.`id`) AS `count`
FROM `t1` LEFT JOIN `t2` ON `t1`.`id` = `t2`.`id`
GROUP BY `t1`.`id`

Left join ensures you have all rows from t1, and COUNT(t2.id) makes it count only records where t2.id is not null (that is - those that really exist in t2)

Incidently
Thanks for your help. I'd like to be able to sort by the `count` descending. (or `name` ASC) is that possible?
Steve
Hm... your solution shows '1' for `count` if there are now rows in t2
Steve
just add "Order by count DESC" in the end
Dheer
Steve: if it shows 1 - maybe you just put COUNT(t1.id), and not COUNT(t2.id)? it makes a huge difference...
Incidently
@Incidently Cheers. :)
Steve
+1  A: 

This sorts descending by COUNT, and within same counts ascending by name. Names with no rows in t2 will return with a count of 0.

SELECT 
  `t1`.`name`, 
  COUNT(`t2`.`id`) AS `count`
FROM 
  `t1` 
  LEFT JOIN `t2` ON`t2`.`id` = `t1`.`id`
GROUP BY
  `t1`.`name`
ORDER BY
  COUNT(`t2`.`id`) DESC,
  `t1`.`name`

Modify the ORDER BY to your needs.

Tomalak
Cheers, however `count` displays `1` when there are no rows in t2
Steve
Oh. sure. I'll correct that.
Tomalak