找到数据库中的最大数字并创建新变量

时间:2013-04-03 06:51:16

标签: php

所以,我在数据库上有这个表,我有这样的字符:

A102
A897
B234
B23
C9823
C786
D345 etc...

我需要达到的目标是: 如果用户已输入A,则该函数应查看以A开头的所有变量 即 我有 : A102和A897,我应该删除第一个字符,并且仍然有102和897。 其中最大的是897,所以我应该创建一个新变量A(897 + 1)= A898,依此类推。 查询:

while( $row = mysql_fetch_assoc( $result)){
    $value[] = $row['id']; // Inside while loop
}

我想它应该是这样的:

   if ($variable==A) {
    $items = array();
    foreach($value as $value) {
     $items[] = substr('$value', 1);
    max($items); // to find max
    }
   }

方法

$result = "SELECT * FROM formas WHERE 'id_f' LIKE '%A%'" ;  
$res = odbc_exec($connection, $result) or die(odbc_error());



    $biggest = 0;
    while( $row = odbc_fetch_array($res))
    {
         $current_value = substr($row['id_f'], 1); // return: 102, 897;
         if( $current_value > $biggest )
         {
            $biggest = $current_value; // in the last looping you should get 897.
         }
    }
    echo $result = "A(" . ($biggest + 1) . ")"; // return A(898)

3 个答案:

答案 0 :(得分:1)

我不确定传递参数。试试这个SQL

SELECT DER_NAME ||CHAR(COUNTER + 1)
FROM 
(
SELECT SUBSTR(NAME, 1) AS DER_NAME, MAX(INT(SUBSTR(2, NAME))) AS COUNTER
FROM TABLE-NAME
WHERE NAME LIKE 'A%' --SUBSTITUE YOUR PARAMETER
group by SUBSTR(NAME, 1)
) A

答案 1 :(得分:0)

我认为可以通过这个程序解决,如果我错了,请纠正我。 (1)。您应该创建一个从用户输入中获取第一个字符的函数。示例:ABC233,函数应为return "A"(2)从步骤1获取字符后,可以将其查询到表。这是完整的源代码:

> <?php  
> mysql_connect("localhost", "root","");
> mysql_select_db("stackoverflow");
> 
> 
> /* First chars */ 
> function first_char( $str ) 
> {
>     return substr($str, 0, 1); 
> } 
> ?>
> 
> <form action="home.php" method="post"> 
>      Input String : <input type="text" name="txtstring"><br> 
>      <input type="submit" value="Submit">
> </form>
> 
> <?php 
> if( $_POST['txtstring'] != '' ) 
> {    
>    $char = first_char($_POST['txtstring'] );    
>    $sql = mysql_query("SELECT * FROM mytablWHERE my_field LIKE '%" . $char . "%'") or die(mysql_error());
>  
>    
>     $biggest = 0;
>     while( $row = mysql_fetch_array($sql))
>     {
>          $current_value = substr($row['my_field'], 1); // return: 102, 897;
>          if( $current_value > $biggest )
>          {
>             $biggest = $current_value; // in the last looping you should get 897.
>          }
>     }
>     $result = "A(" . ($biggest + 1) . ")"; // return A(898)
>      
>     echo $result;
> 
> } ?>

我假设有一个名为“stackoverflow”的数据库和名为“mytable fields:(ID,my_field)”的表 结果是这样的:

enter image description here

让我知道它是否有效!

答案 2 :(得分:0)

(SELECT MAX(N) as maxid FROM (
SELECT CAST(SUBSTR(name, 2) AS UNSIGNED INTEGER) as N 
From `mytable` 
) t)

UNION ALL

(SELECT N as maxid FROM (
SELECT CAST(SUBSTR(name, 2) AS UNSIGNED INTEGER) as N 
From `mytable` 
ORDER BY N DESC) t LIMIT 1)

SQL Fiddle DEMO

您只需使用一个查询:

SELECT MAX(N) as maxid FROM (
    SELECT CAST(SUBSTR(name, 2) AS UNSIGNED INTEGER) as N 
    From `mytable` 
    ) t