GroupByAndMax.sql

    1. --按照user_id分组,分组获得的记录为round_num最大的记录:
    2. -- 方法一:
    3. SELECT
    4. a.activity_id,
    5. a.activity_round_id,
    6. a.round_num,
    7. a.user_id
    8. FROM
    9. jmf_activity_order AS a
    10. WHERE
    11. a.round_num = (
    12. SELECT
    13. max(b.round_num)
    14. FROM
    15. jmf_activity_order AS b
    16. WHERE
    17. a.user_id = b.user_id
    18. )
    19. GROUP BY a.user_id
    20. -- 方法二:
    21. -- 不同的mysql版本老一点的可以不用limit,新一点的可以用limit不然不会排序,有缺陷
    22. SELECT
    23. a.activity_id,
    24. a.activity_round_id,
    25. a.round_num,
    26. a.user_id
    27. FROM
    28. (
    29. SELECT
    30. *
    31. FROM
    32. jmf_activity_order AS b
    33. ORDER BY
    34. b.round_num DESC
    35. LIMIT 100000
    36. ) AS a
    37. GROUP BY a.user_id
    38. -- 方法三:
    39. SELECT
    40. a.activity_id,
    41. a.activity_round_id,
    42. a.round_num,
    43. a.user_id
    44. FROM
    45. jmf_activity_order AS a
    46. WHERE
    47. NOT EXISTS (
    48. SELECT
    49. b.*
    50. FROM
    51. jmf_activity_order AS b
    52. WHERE
    53. a.user_id = b.user_id
    54. AND b.round_num > a.round_num
    55. )
    56. GROUP BY a.user_id
    57. -- 方法四:
    58. SELECT
    59. a.activity_id,
    60. a.activity_round_id,
    61. a.round_num,
    62. a.user_id
    63. FROM
    64. jmf_activity_order AS a
    65. WHERE
    66. EXISTS (
    67. SELECT
    68. b.*
    69. FROM
    70. jmf_activity_order AS b
    71. WHERE
    72. a.user_id = b.user_id
    73. AND b.round_num > a.round_num
    74. HAVING
    75. count(*) = 0
    76. )
    77. GROUP BY a.user_id