[英]Find the largest number in the database and create new variable
所以,我在數據庫上有此表,並且我有這樣的字符:
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)
我不確定傳遞參數。 試試這個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)。 您應該創建一個從用戶輸入中獲取第一個字符的函數。 示例: 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字段:(ID,my_field)”的表,結果如下:
讓我知道它是否有效!
(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)
您可以只使用一個查詢:
SELECT MAX(N) as maxid FROM (
SELECT CAST(SUBSTR(name, 2) AS UNSIGNED INTEGER) as N
From `mytable`
) t
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.