简体   繁体   中英

SQL greater than but the least

let this be my table:

id    timestamp
1     100
2     102
3     102
4     104

I want to query SQLite the record with the timestamp greater than 100 stopping when I find one but returning all with that value.

So in the case of timestamp > 100: 2 and 3 (timestamp 102). Not 4 because is 104 ( > 102)

 SELECT * FROM your_table WHERE timestamp = 
    (SELECT timestamp FROM your_table 
          WHERE timestamp > 100 ORDER BY timestamp LIMIT 1);

or

 SELECT * FROM your_table WHERE timestamp = 
    (SELECT MIN(timestamp) FROM your_table WHERE timestamp > 100)

In both cases you're using an internal SELECT statement to determine what timestamp value you're searching for.

I suspect the first version, while a little more complicated to write, will perform better under some indexing situations since it can, in theory, check only a single row to get that timestamp value.

SELECT * FROM tbl
WHERE timestamp = (
SELECT min(timestamp)
  FROM tbl
 WHERE timestamp > 100
)

Here's a SQLFiddle to see the above code in action, and to prove it works.

This should work:

select * from mytable where timestamp =
(  -- second least timestamp
  select min(timestamp) from mytable where timestamp > 
  ( -- least timestamp
    select min(timestamp) from mytable
  )
);

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