-1

My table is:

ORDER ID     LINENUMBER      PRODUCT 
----------------------------------------
    XYZ           0          PHONE
    XYZ           1          COMPUTER
    XXX           0          MOUSE
    XXX           1          TV
    XXX           2          COMPUTER
    ZYY           0          TV
    XKX           0          PHONE
    XKX           1          HEADPHONE  

I want products in last 3 orders

ORDER ID    LINENUMBER       PRODUCT
-------------------------------------------
   XKX           1           HEADPHONE 
   XKX           0           PHONE
   ZYY           0           TV 
   XXX           2           COMPUTER  
   XXX           1           TV 
   XXX           0           MOUSE  
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 8
    How do you define "last three orders"? SQL tables represent *unordered* sets. There is no such thing as the "last three", unless a column specifies the ordering. Also, tag with the database you are using. – Gordon Linoff Nov 18 '19 at 11:31
  • 'select top 3 * from orders order by desc orderid ' does this do your work? – Mahmoud Zakal Nov 18 '19 at 11:37
  • I think you want to try something like this: https://stackoverflow.com/questions/8523374/mysql-get-most-recent-record – Ridh Official Nov 18 '19 at 11:44

1 Answers1

1

Add created_at column to the table with type timestamp with timezone.

Define its value to be by default now(). Now you can pick the last three orders by the latest dates on the table.

On your select query add ORDER BY clause:

...
ORDER BY created_at DESC LIMIT 3;
Naor Levi
  • 1,713
  • 1
  • 13
  • 27