我的表结构如下:
HISTORY_CARD
+----+-----------+---------+--------------+
| idhistory_card |equipment_id | sr_num |
+----+-----------+---------+--------------+
| 1 | DU 201 | 9 |
| 2 | DU 201 | 2 |
| 3 | DU 201 | 12 |
| 4 | EXT 99 | 10 |
| 5 | EXT 99 | 13 |
| 6 | EXT 99 | 7 |
| 7 | EXT 99 | 9 |
+----+-----------+---------+--------------+
我想返回特定euipment_id的coloumn(sr_num)的最大值。例如。对于equipment_id = DU 201,最大值为12但是在下面提到的查询中它返回错误的值,即9 类似地,对于equipment_id = EXT 99,最大值是13,但是对于下面提到的查询,它返回错误的值,即9 。我在互联网上搜索过很多关于手册但直到现在都没有用的东西。请帮忙!
查询如下
SELECT *
FROM new_schema.history_card
WHERE equipment_id = 'DU 201'
ORDER BY sr_num DESC LIMIT 1
2查询尝试
SELECT MAX(sr_num)
FROM new_schema.history_card
WHERE equipment_id='DU 201';
答案 0 :(得分:6)
对字符串值的MAX()
操作将根据字符串比较规则运行,即"9" > "10"
。
答案是更改表定义:
ALTER TABLE history_card MODIFY sr_num INT;
然后,再次运行查询。
答案 1 :(得分:1)
试试这个
SELECT *
FROM new_schema.history_card
WHERE equipment_id = 'DU 201'
ORDER BY CAST(sr_num AS UnSigned) DESC LIMIT 1
或:
SELECT *
FROM new_schema.history_card
WHERE equipment_id = 'DU 201'
ORDER BY sr_num * 1 DESC LIMIT 1