List<Product> productList = productService.list(new LambdaQueryWrapper<Product>().in(Product::getProdId, prodIds));
简单说,mysql的查询会按照主键排序,当你需要参数的顺序关系时,请使用map,而不是直接for循环获取。
例子:
代码中的prodIds假设为 7,6,3
查询后的list id排序为3,6,7
如果此时你认为查询后的list还是按照之前的ID排序,并以这个关系操作时就会有问题。
后续补充
发现这个问题和索引有关
select p.* from dy_doudian_prod p where p.product_id in (3508823072759261766,3509226009411078761,35088610555290529230,3509217952245406923)
使用普通索引时,查询应该通过普通索引查找,但是返回顺序按id排序
select p.product_id from dy_doudian_prod p where p.product_id in (3508823072759261766,3509226009411078761,35088610555290529230,3509217952245406923)
使用覆盖索引时 查找结果顺序按照索引顺序排列
select p.product_id from dy_doudian_prod p where p.id in (1,4,7,8,5);
使用主键索引时 查找结果顺序按照主键索引排序
比较有疑问的第一种情况,第一种情况查询肯定是用索引,如果使用索引那么回表查询后的数据中id一定乱序,而目前情况是排序的,说明做了排序,我们知道排序需要在内存中创建临时排序表,消耗系统资源。
那么当我们没有指定排序参考列时就是默认主键排序吗?