简体   繁体   English

MySQL:顺序,限制,顺序

[英]MySQL: Order, Limit, Order

I try to program a solution where I have multiple linked tables. 我尝试编写一个具有多个链接表的解决方案。 Now I have another problem: 现在我有另一个问题:

I want to limit count of returned lines to 1000. But I want to show ID 1-1000, next page 1001-2000. 我想将返回的行数限制为1000。但是我想显示ID 1-1000,下一页1001-2000。 IDs may be stored in iregular order in database (ID 1 does not have to be the first row) ID可以以不规则的顺序存储在数据库中(ID 1不必是第一行)

Not any problem so far: 到目前为止没有任何问题:

SELECT * FROM table ORDER BY id ASC LIMIT 1000

BUT Now I have to sort resulty by another column: 但是现在我必须按另一列对结果进行排序:

SELECT * FROM table ORDER BY name ASC LIMIT 1000

which might return other IDs than 1-1000 or I do 可能会返回1-1000以外的其他ID或我这样做

SELECT * FROM table ORDER BY id ASC, ORDER BY name ASC LIMIT 1000

But this will only sort by ID an then by name. 但这只会按ID排序,然后按名称排序。 So if I would have any ID as duplicate (which is not possible) I would then have those sorted by name. 因此,如果我将任何ID重复(这是不可能的),那么我将按照名称对它们进行排序。

How can I achive that I get the first 1000 IDs (some IDs might not exist as they might have been deleted before!) and those thousand rows sorted by name? 如何获得前1000个ID(某些ID可能不存在,因为它们可能之前已被删除过!),然后按名称对那1000行进行排序?

Is that even possible? 那有可能吗?

Try this: 尝试这个:

SELECT * FROM table WHERE id IN (
   SELECT ID FROM table ORDER BY ID ASC LIMIT 0, 1000
) ORDER BY name ASC

As mentioned in comments that subquery is not supported, 'This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'. 如注释中所述,不支持子查询,“此版本的MySQL尚不支持“ LIMIT&IN / ALL / ANY / SOME子查询”。 Using JOINs is the only alternative left, like this: 剩下的唯一选择就是使用JOIN,如下所示:

SELECT table.* FROM tab JOIN (
   SELECT ID FROM table ORDER BY ID LIMIT 1000
) temp
ON table.ID = temp.ID
ORDER BY table.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM