database - strange MySQL join query results with aggregate functions -
i wrote following join query report using aggregate functions
select users.id, sum(orders.totalcost) bought, count(comment.id) commentscount, count(topics.id) topicscount, count(users_login.id) logincount, count(users_download.id) downloadscount users left join orders on users.id=orders.userid , orders.paystatus=1 left join comment on users.id=comment.userid left join topics on users.id=topics.userid left join users_login on users.id=users_login.userid left join users_download on users.id=users_download.userid group users.id order bought desc
but don't know why following output?
the result of aggregate functions multiplied each other!!!
i don't know why?
for example last row expected following result
821 | 48000 | 63 | 0 | 10 | 10
the result of executing explain query shown below
one reason type of result using left joins users table , result set may contains duplicate rows each user getting count more expected 1 can use distinct
in count count unique associations per user , sum of totalcost
can use subselect have sum each user without having repeated values orders of user
select u.id, coalesce(o.bought,0) bought count(distinct c.id) commentscount, count(distinct t.id) topicscount, count(distinct ul.id) logincount, count(distinct ud.id) downloadscount users u left join (select userid, sum(totalcost) bought orders paystatus=1 group userid) o on u.id=o.userid left join `comment` c on u.id=c.userid left join topics t on u.id=t.userid left join users_login ul on u.id=ul.userid left join users_download ud on u.id=ud.userid group u.id order bought desc
Comments
Post a Comment