You get a bonus - 1 coin for daily activity. Now you have 1 coin

Common mistakes in writing SQL queries

Lecture



1. MySQL joins combined with SUM and COUNT can return an incorrect result

example

SELECT
 t1.name,
 COUNT(t2.id),
 SUM(t2.total)
FROM users t1
LEFT JOIN  orders t2 ON t1.id = t2.user_id

GROUP BY t1.id

In this case, what gets summed is not the sum of orders for each user, but

the sum of each user's orders multiplied by the number of users,

this can be fixed by using a subquery

SELECT
 t1.name,
cnt,
 amount
FROM users t1
LEFT JOIN
( select
user_id
COUNT(t2.id) as cnt,
 SUM(t2.total) as amount
from orders
group by user_id
)
t2 ON t1.id = t2.user_id

GROUP BY t1.id

See also

  • [[b5954]]

See also

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Databases, knowledge and data warehousing. Big data, DBMS and SQL and noSQL"

Terms: Databases, knowledge and data warehousing. Big data, DBMS and SQL and noSQL