简体   繁体   中英

Best Way to form this query

Team,

I have three tables.

myTransTable,myMasterTable 1, MymyMasterTable 2

myTransTable have a lot of entries 'Rank.No ' auto incerement field is to identify indvidual records . 'U.Name' holds user name. Each user can have multiple records in this table . But the most recent transaction of a user can be find by the max value for Rank.No after grouping by 'U.Name'

Once this max record ie recent transaction is fetched their asociated data needs to fetched from other tables

How can this be done in most efficent way.

1.myTransTable(fields Rank.No(auto increment field),Name,RecNum,uname,date,type)

2.myMasterTable1 (RecNum,Recowner,recdate)

3.MymyMasterTable2 (uName,age ,address,contact num)

I tried these ways for selection the max record and fetch the assocated data from other tables

  1. max records as a view and fetch data from other tables using normal query
  2. Max records and associated data itself as a view and select data as needed

Which is best way to have minimum execution time?

My queries are which is the best way to find the max.

Option one

select a.`RecNum`,a.`Name`,a.`Date`, a.`type`"+
            "from myTransTable a "+
            "INNER JOIN "+
            "(SELECT RecNumMAX(`Rank.No`) AS maxserialnum FROM myTransTable "+
            "GROUP BY RecNumMAX)groupedRecNumMAX "+
            " ON "+
            " a.RecNum = groupedPWO.RecNum  "+
            "AND "+
            "a.`Rank.No`  = groupedRecNumMAX.maxserialnum "+

Option two

Select a.`RecNum`,a.`Name`,a.`Date`, a.`type`"+` 
FROM                   from myTransTable a

WHERE                    s.`RecNum` in(select MAX(`RecNum`)
       from               myTransTable 
       group by       RecNum)

This is just a suggestion adn is related to your first query .. that seems contain wrong reference to table and column name

looking to you code you should use a query like this

select a.`RecNum`
    ,a.`Name`
    ,a.`Date`
    , a.`type`
  from myTransTable a 
  INNER JOIN   (
      SELECT RecNum, MAX(`Rank.No`) AS maxserialnum 
      FROM myTransTable 
      GROUP BY RecNum 
  )  g ON  a.RecNum =g.RecNum  AND  a.`Rank.No`  = g..maxserialnum 

and this with proper index .. on RecNum, and Rank.No should be the most performant (you can check in explain plain and with proper execution test)

You should not use column name with dot separated name as Rank.No .. use Rank_No isteand and also for column name the is preferred lowercase not and not a mix of UpperOrLower case use underscore for separate the word instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM