简体   繁体   中英

SQL - How to select discontinuous rows from a table with one select?

 `SELECT * FROM Post
  WHERE Tid = Id
  ORDER BY Time
  LIMIT 0,1`

 `SELECT * FROM Post
  WHERE Tid = Id
  ORDER BY Time
  LIMIT start,offset;`

Can I use only one SELECT to complete this? Just like

  `SELECT * FROM Post
  WHERE Tid = Id
  ORDER BY Time
  LIMIT 0,1 and start,offset;`

In this case combine the 2 sql statements in a union, since you cannot provide multiple limit clauses in a single select:

SELECT * FROM Post LIMIT 1,2
UNION ALL
SELECT * FROM Post LIMIT 5,6;

However, I would add an order by clause to the 2 select statements just to make 100% sure you know which records will be selected.

UPDATE: Technically you could do this in a single statement using a running counter and filtering on the counter in where. However, that would not really be a good idea from performance wise, since mysql would have to loop through all records within the table. It cannot know which records would satisfy the criteria. Limit clauses are better optmised.

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