Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- SELECT u.id AS ForUserId, nec.NumComments AS NumEntryComments, nic.NumComments AS NumImageComments
- FROM users u
- LEFT JOIN (
- SELECT e.user_id AS ForUserId, SUM(ce.NumComments) AS NumComments FROM entries e
- JOIN (
- SELECT entry_id, count(*) AS NumComments FROM `comments_entries` GROUP BY entry_id
- ) AS ce ON e.id = ce.entry_id
- GROUP BY ForUserId
- ) AS nec ON nec.ForUserId = u.id
- LEFT JOIN (
- SELECT i.user_id AS ForUserId, SUM(ci.NumComments) AS NumComments FROM images i
- JOIN (
- SELECT image_id, count(*) AS NumComments FROM `images_comments` GROUP BY image_id
- ) AS ci ON i.id = ci.image_id
- GROUP BY ForUserId
- ) AS nic ON nic.ForUserId = u.id
- WHERE u.status = 3
- AND (nec.NumComments IS NOT NULL OR nic.NumComments IS NOT NULL);
- /*
- regular results:
- +-----------+------------------+------------------+
- | ForUserId | NumEntryComments | NumImageComments |
- +-----------+------------------+------------------+
- | 1 | 20 | 88 |
- | 29 | NULL | 3 |
- | 61 | NULL | 6 |
- | 69 | NULL | 6 |
- +-----------+------------------+------------------+
- 4 rows in set (0.03 sec)
- with SUM(nec.NumComments + nic.NumComments) AS NumComments:
- +-----------+------------------+------------------+-------------+
- | ForUserId | NumEntryComments | NumImageComments | NumComments |
- +-----------+------------------+------------------+-------------+
- | 1 | 20 | 88 | 108 |
- +-----------+------------------+------------------+-------------+
- 1 row in set (0.00 sec)
- with SUM(COALESCE(nec.NumComments,0) + COALESCE(nic.NumComments,0)) AS NumComments:
- +-----------+------------------+------------------+-------------+
- | ForUserId | NumEntryComments | NumImageComments | NumComments |
- +-----------+------------------+------------------+-------------+
- | 1 | 20 | 88 | 123 |
- +-----------+------------------+------------------+-------------+
- 1 row in set (0.00 sec)
- What the... it SUM'd all the rows together?!
- */
Add Comment
Please, Sign In to add comment