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条)

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私