0

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

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

3 回答 3

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
于 2013-04-03T06:58:10.127 回答
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)”的表,结果如下:

在此处输入图像描述

让我知道它是否有效!

于 2013-04-03T07:26:29.247 回答
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 演示

您可以简单地使用一个查询:

SELECT MAX(N) as maxid FROM (
    SELECT CAST(SUBSTR(name, 2) AS UNSIGNED INTEGER) as N 
    From `mytable` 
    ) t
于 2013-04-03T07:56:47.933 回答