Guest User

Untitled

a guest
Jun 19th, 2018
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. SELECT u.id AS ForUserId, nec.NumComments AS NumEntryComments, nic.NumComments AS NumImageComments
  2. FROM users u
  3.  
  4. LEFT JOIN (
  5. SELECT e.user_id AS ForUserId, SUM(ce.NumComments) AS NumComments FROM entries e
  6. JOIN (
  7. SELECT entry_id, count(*) AS NumComments FROM `comments_entries` GROUP BY entry_id
  8. ) AS ce ON e.id = ce.entry_id
  9. GROUP BY ForUserId
  10. ) AS nec ON nec.ForUserId = u.id
  11.  
  12. LEFT JOIN (
  13. SELECT i.user_id AS ForUserId, SUM(ci.NumComments) AS NumComments FROM images i
  14. JOIN (
  15. SELECT image_id, count(*) AS NumComments FROM `images_comments` GROUP BY image_id
  16. ) AS ci ON i.id = ci.image_id
  17. GROUP BY ForUserId
  18. ) AS nic ON nic.ForUserId = u.id
  19.  
  20. WHERE u.status = 3
  21.  
  22. AND (nec.NumComments IS NOT NULL OR nic.NumComments IS NOT NULL);
  23.  
  24.  
  25.  
  26. /*
  27. regular results:
  28. +-----------+------------------+------------------+
  29. | ForUserId | NumEntryComments | NumImageComments |
  30. +-----------+------------------+------------------+
  31. | 1 | 20 | 88 |
  32. | 29 | NULL | 3 |
  33. | 61 | NULL | 6 |
  34. | 69 | NULL | 6 |
  35. +-----------+------------------+------------------+
  36. 4 rows in set (0.03 sec)
  37.  
  38.  
  39. with SUM(nec.NumComments + nic.NumComments) AS NumComments:
  40. +-----------+------------------+------------------+-------------+
  41. | ForUserId | NumEntryComments | NumImageComments | NumComments |
  42. +-----------+------------------+------------------+-------------+
  43. | 1 | 20 | 88 | 108 |
  44. +-----------+------------------+------------------+-------------+
  45. 1 row in set (0.00 sec)
  46.  
  47.  
  48. with SUM(COALESCE(nec.NumComments,0) + COALESCE(nic.NumComments,0)) AS NumComments:
  49. +-----------+------------------+------------------+-------------+
  50. | ForUserId | NumEntryComments | NumImageComments | NumComments |
  51. +-----------+------------------+------------------+-------------+
  52. | 1 | 20 | 88 | 123 |
  53. +-----------+------------------+------------------+-------------+
  54. 1 row in set (0.00 sec)
  55.  
  56.  
  57. What the... it SUM'd all the rows together?!
  58. */
Add Comment
Please, Sign In to add comment