获取mysql DB中列的最大值

时间:2012-10-06 05:59:44

标签: mysql sql

我的数据库表列值为

tenant_ id  group_id
2           2-100
2           2-111
1           1-222
1           1-888
2           2-999 
2           2-1000

查询:

select max(group_id) from prospect_group where tenant_id=2

我已经使用上面的查询来获取tenant_id = 2的最大值,但它返回的值为999而不是1000.如何获得1000作为最大值。???任何人都可以帮助我.. ???

2 个答案:

答案 0 :(得分:5)

您需要GROUP BY子句

SELECT tenant_ID, MAX(CAST(group_ID AS SIGNED))
FROM tableName
-- WHERE  tenant_id=2 -- uncomment this if you select only for specific tenant_ID
GROUP BY tenant_ID

通过替换为空字符来尝试。

SELECT tenant_ID, 
       MAX(CAST(REPLACE(group_ID, CONCAT(tenant_ID, '-'), '')  AS SIGNED)) maxGID
FROM tableName
-- WHERE  tenant_id=2 -- uncomment this if you select only for specific tenant_ID
GROUP BY tenant_ID

SQLFiddle Demo

答案 1 :(得分:1)

您需要添加GROUP BY子句。

select max(group_id) from prospect_group where tenant_id=2 group by tenant_ id