SELECT *在MAX和第二个MAX id之间的列WHERE另一列等于某个输入

时间:2015-03-19 14:25:00

标签: php mysql sql

我有一个名为orders的表,其中包含(a.o.)列sidq1_requested_bysid列包含唯一的ID号,每个新输入都会递增。

有时会在q1_requested_by列中输入值ORDERS PROCESSED

我想从表格中选择介于最新ÒRDERS PROCESSED输入和最新但只有ORDERS PROCESSED输入之间的所有内容。

我尝试过以下操作,但不起作用。它什么都不选。

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

我怎么解决这个问题?

3 个答案:

答案 0 :(得分:1)

您好,您可以添加限制到查询的第二部分。请试试这个:

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

答案 1 :(得分:1)

首先,您将使用MySQL构造:

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

答案 2 :(得分:0)

它会起作用:)

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