尝试从一个需要几个连接和一些数学的表中获取一个简单的SUM和COUNT。我无法做对。
我有4张桌子:
USERS
user_id, name
1, user1
2, user2
3, user3
4, user4
RESULTS
user_id, plus, minus
1, 1, 0
1, 1, 0
1, 1, 0
3, 0, 1
3, 1, 0
3, 1, 0
3, 1, 0
NOTES
user_id, note
1, lorem ipsum
3, abc
1, qwerty
3, qwerty
MESSAGES
user_id, message
1, lorem ipsum
3, abc
1, qwerty
3, qwerty
3, qwerty
3, qwerty
3, qwerty
我想总结从减号,笔记数量和用户消息数量中减去加号的所有结果。
我的查询:
SELECT u.`user_id`, SUM(w.`plus`-w.`minus`), COUNT(g.`user_id`), COUNT(m.`user_id`)
FROM `users` u
LEFT JOIN `results` w ON u.`user_id` = w.`user_id`
LEFT JOIN `notes` g ON u.`user_id` = g.`user_id`
LEFT JOIN `messages` m ON u.`user_id` = m.`user_id`
GROUP BY 1
预期结果如下:
user_id: sum(plus-minus) amount of notes, amount of messages
1: 3, 2, 2
3: 2, 2, 5
不幸的查询返回:
user_id: sum(plus-minus) amount of notes, amount of messages
1: 12, 12, 12
3: 20, 40, 40
非常感谢任何帮助。
答案 0 :(得分:1)
您应该为每个user_id
手动计算子查询中的记录,以便获得正确的值。
SELECT u.user_ID, u.Name,
COALESCE(r.totalResult, 0) totalResult,
COALESCE(n.totalNotes, 0) totalNotes,
COALESCE(m.totalMessages, 0) totalMessages
FROM users u
LEFT JOIN
(
SELECT user_ID, SUM(plus - minus) totalResult
FROM Results
GROUP BY user_ID
) r ON u.user_ID = r.user_ID
LEFT JOIN
(
SELECT user_ID, COUNT(*) totalNotes
FROM Notes
GROUP BY user_ID
) n ON u.user_ID = n.user_ID
LEFT JOIN
(
SELECT user_ID, COUNT(*) totalMessages
FROM Messages
GROUP BY user_ID
) m ON u.user_ID = m.user_ID
但是如果您在每个表中都设置了auto_incremented
列,则不需要子查询,因为您可以从中明确计算。