简体   繁体   English

MySQL命令受限制混乱

[英]MySQL order by limit confusion

I get a problem today. 我今天有问题。 Here is my jobs table: 这是我的工作表:

select id,name,is_active from jobs order by `is_active` desc

and result is : 结果是:

在此处输入图片说明

But when I want to get first 10 records I select this: 但是,当我想获得前10条记录时,请选择以下内容:

select id,name,is_active from jobs order by `is_active` desc limit 10 offset 0

And result is 结果是

在此处输入图片说明

Why id is from 14 to 5, it should be 1 to 10. Who can tell me why? 为什么id是14到5,应该是1到10。谁能告诉我为什么?

if you want a deeper order you must explicitly require it otherwise the result will be unpredictable. 如果您想获得更深层次的订单,则必须明确要求它,否则结果将无法预测。 So if you need the id order too, add it. 因此,如果您也需要ID顺序,请添加它。

select id,name,is_active from jobs order by `is_active` desc, id asc limit 10 offset 0

In MySQL, if not specified explicitly then order is arbitrary. 在MySQL中,如果未明确指定,则顺序是任意的。 You should try order by id asc . 您应该尝试order by id asc

You need to use multiple columns in ORDER BY , eg: 您需要在ORDER BY使用多个列,例如:

SELECT id, name, is_active 
FROM jobs 
ORDER BY `is_active` DESC id ASC;

If you need to keep the result in descending order, and still only want the 10 last id's you should sort your result two times. 如果您需要将结果按降序排列,而仍然只希望最后10个ID,则应该对结果进行两次排序。

This query below will sort the result ascending and limit the result to 10 (that is the query inside the parenthesis). 下面的查询将对结果进行升序排序,并将结果限制为10(即括号内的查询)。 It will still be sorted in ascending order, and we are not satisfied with that, so we sort it one more time. 它仍然会按升序排序,我们对此并不满意,因此我们再对其进行排序。 Now we have the newest result on the last row. 现在,我们在最后一行获得了最新的结果。

select t.id, t.name, t.is_active 
from 
    (select id, name, is_active 
     from jobs 
     order by `is_active` asc limit 10) t 

order by t.is_active desc;

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

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