Getting the last record in SQL in WHERE condition

后端 未结 9 2281
借酒劲吻你
借酒劲吻你 2021-02-15 04:24

i have loanTable that contain two field loan_id and status

loan_id status
==============
1       0
2       9
1       6
         


        
9条回答
  •  攒了一身酷
    2021-02-15 04:32

    Since the 'last' row for ID 1 is neither the minimum nor the maximum, you are living in a state of mild confusion. Rows in a table have no order. So, you should be providing another column, possibly the date/time when each row is inserted, to provide the sequencing of the data. Another option could be a separate, automatically incremented column which records the sequence in which the rows are inserted. Then the query can be written.

    If the extra column is called status_id, then you could write:

    SELECT L1.*
      FROM LoanTable AS L1
     WHERE L1.Status_ID = (SELECT MAX(Status_ID)
                             FROM LoanTable AS L2
                            WHERE L2.Loan_ID = 1);
    

    (The table aliases L1 and L2 could be omitted without confusing the DBMS or experienced SQL programmers.)

    As it stands, there is no reliable way of knowing which is the last row, so your query is unanswerable.

提交回复
热议问题