dqt66847 2012-03-30 22:17
浏览 27
已采纳

查找两个varchar字段的最大数值

I'm trying to find the max value contained in two separate fields of my table.

The code I'm using in my model is:

$query = $this->db->query("select max($field1) as max_id_1 from default_table1");
$row1 = $query->row_array();
$query = $this->db->query("select max($field2) as max_id_2 from default_table1");
$row2 = $query->row_array();
return max($row1['max_id_1'], $row2['max_id_2']);

I'm a complete novice where PHP and CodeIgniter is concerned - as I'm sure my code demonstrates :)

It is working insofar as it's returning values, but not the maximum values I have in the fields. For instance I know there is a 4000 value but the highest returned is 750.

I'm wondering if this is because the fields are of type VARCHAR because although they predominantly contain numbers there are some that contain characters (- or &) or the word 'to' so I couldn't use the INT type. Because of using VARCHAR is it failing to see that 4000 is larger than 750?

If so is there a way to cast the field contents as integer before checking for the max value, and will this be affected by the non-integer values in the fields?

All offers of help and advice is gratefully received.

Tony.

  • 写回答

3条回答 默认 最新

  • douyun1546 2012-03-30 22:34
    关注

    This can be done using SQL using MySQL's implicit type conversion:

    select max(case when (field1+0)>(field2+0) then field1+0 else field2+0 end)
    from default_table1
    

    Using +0 would convert varchar to number and also ignore any characters that follow after the number. If you still need the original content, you can write the query like this:

    select case when (field1+0)>(field2+0) then field1 else field2 end
    from default_table1
    order by case when (field1+0)>(field2+0) then field1+0 else field2+0 end desc
    limit 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题