【问题标题】:MySQL max and MIN function showing 100 and above as minimum valueMySQL max 和 MIN 函数显示 100 及以上作为最小值
【发布时间】:2021-09-21 02:49:28
【问题描述】:

我进行了查询以显示数据库中的最大值和最小值,但它不能完美运行。如果我们有 100 及以上的值,则返回最低而不是 99 及以下

SELECT MIN(total) AS min, MAX(total) AS max  FROM `results` WHERE `term_id` = 2 AND  `class_id` = 8 AND `subject_id` = 152

结果

min     max     
100     96

这是我的表结构:

CREATE TABLE `results` (
  `rst_id` bigint(20) NOT NULL,
  `user_id` int(11) NOT NULL,
  `subject_id` int(11) NOT NULL,
  `first_test` varchar(2) DEFAULT NULL,
  `second_test` varchar(2) DEFAULT NULL,
  `exam` varchar(2) DEFAULT NULL,
  `total` varchar(3) NOT NULL,
  `position` int(11) DEFAULT NULL,
  `term_id` int(11) NOT NULL,
  `session_id` int(11) NOT NULL,
  `class_id` int(11) NOT NULL,
  `is_new` tinyint(1) DEFAULT '1',
  `is_upd` tinyint(1) NOT NULL DEFAULT '0',
  `date_declared` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `date_updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `declared_by` int(11) NOT NULL,
  `updated_by` int(11) DEFAULT NULL,
  `deleted` tinyint(1) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

【问题讨论】:

  • 请提供原始表作为创建表和数据作为文本或小提琴。因为我认为你没有整数值,你可能有 char 或 varchar
  • 这是一个链接小提琴db-fiddle.com/f/w19Edb3V9NNqSBuhtGWc3B/0
  • 你得到了一个 varchar 的最小值和最大值(在你的小提琴中总计是 varchar,它应该是整数)。当你使用varchar时,100在96之前(低于),因为1在9之前,并且系统使用字母顺序,没有数字顺序

标签: mysql sql max min


【解决方案1】:

我以为你有一个 varchar,它是按字典顺序排序的

使用

SELECT MIN(total + 0) AS min, MAX(total + 0) AS max  
FROM `results` 
WHERE `term_id` = 2 AND  `class_id` = 8 AND `subject_id` = 152

这会将其转换为数字

【讨论】:

    猜你喜欢
    • 2015-04-05
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2017-12-07
    • 2010-12-19
    • 2023-03-26
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多