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

后端 未结 2 1896
温柔的废话
温柔的废话 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条回答
  • As Golez says, with such amount of data, query might be slow.

    Maybe you should keep track of max paycheck, not ask db every time?

    You can do it from you program, or using triggers. Depends on you.

    In this case you will have to execute your query just once, to fill table with initial data, and then it will update automaticly

    0 讨论(0)
  • 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. ;-)

    0 讨论(0)
提交回复
热议问题