Wednesday, December 12, 2007

Tricks to use multiple group by within a single query

Here, I have 3 tables: users, photos, and friends. Each user has many photos and friends. I face one problem when I want to join to these two tables to get the total number of photos and friends of a specific user with a single query. Here is my first query I wrote that returns incorrect information:

SELECT
u.id, COUNT(p.user_id) as total_photo, COUNT(f.user_id) as total_friend
FROM
friends as f RIGHT JOIN (
photos as p RIGHT JOIN users as u ON p.user_id = u.id)
ON f.user_id = u.id
WHERE
u.id = 1070
GROUP BY
p.user_id

The reason would cause from GROUP BY. My friend, sophy, advised me to join users with photos first then make it as derived table. Last join it with friends, it works. Here is my query, but it is seems too complicated:

SELECT
t_photo.*, COUNT(f.user_id) as total_friend
FROM (
SELECT u.id as user_id, COUNT(p.user_id) as total_photo
FROM
users as u LEFT JOIN photos as p ON u.id = p.user_id
WHERE
u.id = 1070
GROUP BY
p.user_id
) AS t_photo
LEFT JOIN friends as f ON f.user_id = t_photo.user_id
GROUP BY t_photo.user_id

No comments:

Subscribe in a Reader