Ordering a MySQL result set by a MAX() value of another table

后端 未结 2 1895
温柔的废话
温柔的废话 2020-12-22 12:17

Let\'s say I have two tables.

Table 1: Employee roster

| ID | Name        |
| ---| ------------|
|  1 | Joe         |
|  2 | Jim         |
|  3 | Ja         


        
2条回答
  •  轮回少年
    2020-12-22 12:54

    select
      p.ID,
      e.NAME
    from
      Paychecks p
      inner join Employee e on p.EmployeeID = e.ID
    group by
      p.ID
    order by
      max(p.AmountPaid) desc
    

    A different way of writing, which looks more logical, but may be slower (you'd have to test) is:

    select
      e.ID,
      e.NAME
    from
      Employee e
      inner join Paychecks p on p.EmployeeID = e.ID
    group by
      e.ID
    order by
      max(p.AmountPaid) desc
    

    With tens of millions of rows, every query is growing slow sometimes, but with the proper indexes, this is as fast as it gets. I think you basically need one index on Paychecks.EmployeeID and Paychecks.AmountPaid combined. And index on Employee.ID may help.

    If the join is killing you in the end, you may execute two queries. The first one only uses the paychecks to group them by EmployeeID and order them by the max(PaycheckAmount), and a second one can be used to fetch the names for each ID. Sometimes joins cost more performance than you'd like, and when you got 10 million paychecks for 500 employees, it may be faster to do it in two steps, although it will mean that they have been working at the company for about 1600 years avarage. ;-)

提交回复
热议问题