mysql - 使用 min(key) 得到意外结果

标签 mysql sql database

我有两个表 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()与非聚合列一起运行,例如 idisalive .我相信 MySQL 不保证 哪个 id它将与该列的最小值一起返回。

我的策略是按server_counts 升序返回所有 行, 然后到 SELECT只有第一行(这是最少的)。

关于mysql - 使用 min(key) 得到意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30497921/

相关文章:

mysql - DSUM Access 查询中的现有字段

php - 提交 html 表单而不执行任何操作

sql - 在没有准备好的语句/SQLite/C++ 的情况下防止 SQL 注入(inject)

mysql - 使用mysql删除命令时,锁总数超过锁表大小

mysql - 了解在右侧元素上使用 AND 的左外连接,仍然会导致重复条目(使用 sql fiddle)

mysql - 将两个表中的值合并为给定的用户名

php - 使用PHP错误将HTML表单中的数据输入到MYSQL

mysql - 无法使用 group by 在 sql 中合并两个查询

sql - MySQL:一位的最小数据类型

php - MySQL JSON 数据类型是否不利于数据检索的性能?