简体   繁体   中英

SELECT * in between MAX and second MAX id of a column WHERE another column equals a certain input

I have a table called orders with (ao) columns sid and q1_requested_by . The sid column contains a unique id number, incrementing with every new input.

Every now and then there is an input in column q1_requested_by with the value ORDERS PROCESSED .

I want to select everything from the table which falls in between the latest ÒRDERS PROCESSED input and the latest but one ORDERS PROCESSED input.

I've tried the following, which doesn't work. It selects nothing.

SELECT * FROM orders 
WHERE sid < (SELECT max(sid) FROM orders
             WHERE q1_requested_by = 'ORDERS PROCESSED')
  AND sid > (SELECT TOP 2 sid FROM orders
             WHERE q1_requested_by = 'ORDERS PROCESSED'
             ORDER BY sid DESC)
ORDER BY sid DESC

How could I solve this?

Hi you can just add limit to the second part of the query. Please try this:

SELECT * FROM orders 
WHERE sid < (SELECT max(sid) FROM orders WHERE q1_requested_by = 'ORDERS PROCESSED')
AND sid > (SELECT TOP 2 sid FROM orders 
WHERE q1_requested_by = 'ORDERS PROCESSED' ORDER BY sid DESC LIMIT 1) 
ORDER BY sid DESC

First, you would use MySQL constructs:

SELECT o.*
FROM orders o
WHERE o.sid < (SELECT max(sid)
               FROM orders
               WHERE q1_requested_by = 'ORDERS PROCESSED'
              ) AND
      o.sid > (SELECT sid
               FROM orders
               WHERE q1_requested_by = 'ORDERS PROCESSED'
               ORDER BY sid DESC
               LIMIT 1, 1
              )
ORDER BY o.sid DESC

It will work :)

SELECT * FROM orders 
WHERE sid = (SELECT max(sid) FROM orders WHERE sid <>     
            (SELECT max(sid) FROM orders WHERE q1_requested_by = 'ORDERS PROCESSED'))

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