dozc58418381 2013-09-06 17:57
浏览 12

查找最低可用功能

I'm trying to create function which will return for my script lowest available id of current user. For example, let's say, there's user with id 25, so he will be able to enter 10addresses, numbered from 250 to 259. So i created this function:

protected function checkAvailIDforAddress($id)
{

    $min = $id*10;
    $max = $id*10 + 9;

    $checkAvailID = $this->_dbconnection->prepare
            ('SELECT MAX(user_id) FROM user_address WHERE user_id BETWEEN :min AND :max');

    $checkAvailID->bindParam(':min', $min);
    $checkAvailID->bindParam(':max', $max);

    $checkAvailID->execute();

    $row = $checkAvailID->fetch();

    if ($row[0] == 0) throw new Exception('Error');

    $AvailID = $row[0] + 1;

    return $AvailID;


}

I thought, that this function will be good, but then i tested it and i found out, that if user put into db 3addresses, and then deleted 2nd, the function still return max. value, so entry will be added as 4th and 2nd will be unset.

Then I altered the question with foreach loop, and in every loop I made query to db to check, whether is certain id unset, but i think that this query is really uneffective. So my question is: is there some query to db which will return first available id between two values?

  • 写回答

1条回答 默认 最新

  • dongzaotiao2863 2013-09-06 18:03
    关注

    Hate to say this, but your question makes absolutely no sense.

    I will point out that if you are looking for the LOWEST possible user_id, using SELECT MAX(user_id) is the opposite of what you want...

    If you want a range, use SELECT MIN(user_id) as min, MAX(user_id) as max ....

    'SELECT MIN(user_id) as min, MAX(user_id) as max FROM user_address WHERE user_id BETWEEN :min AND :max'
    

    If your results, you will now have a 'min' and 'max' value that you can use to determine a range of available ID's?

    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)