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:
Post a Comment