我有两个表 ss_test 和 ss_ceastore_config ss_test 有一个名为 store_id 的字段,它映射到 ss_ceastore_config id。 我的 ss_test 包含服务器条目,告诉它正在使用哪个商店 所以我试图找到哪个商店使用的时间最少及其 ID。 我写了以下查询。
select id,
min(server_counts) as server_counts,
isalive
from (select ss_ceastore_config.id ,
count(server_id)as server_counts,
ss_ceastore_config.isalive
from ss_test
right join ss_ceastore_config
on ss_test.store_id = ss_ceastore_config.id
group by store_id
order by id) join_1
我的内部查询给了我如下正确的结果
id Ascending server_counts isalive
1 5 1
2 0 1
所以我想使用 min 函数从内部查询输出中选择以下记录
id Ascending server_counts isalive
2 0 1
但是我的外部查询给出了如下所示的意外结果
id server_counts isalive
1 0 1
为什么会这样?为什么它为 server_counts 0 提供 id 1? 如何修复此查询?
最佳答案
select id,
server_counts,
isalive
from (select ss_ceastore_config.id ,
count(server_id)as server_counts,
ss_ceastore_config.isalive
from ss_test
right join ss_ceastore_config
on ss_test.store_id = ss_ceastore_config.id
group by store_id
order by id) join_1
order by server_counts asc
limit 1;
您的原始查询无效,因为您正在执行聚合 SELECT
使用 MIN()
与非聚合列一起运行,例如 id
和 isalive
.我相信 MySQL 不保证 哪个 id
它将与该列的最小值一起返回。
我的策略是按server_counts
升序返回所有 行, 然后到 SELECT
只有第一行(这是最少的)。
关于mysql - 使用 min(key) 得到意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30497921/