簡體   English   中英

如何從my_table中選擇MAX(column)作為max_value WHERE some_other_column = SQL中的“ something”

[英]How to SELECT MAX(column) as max_value FROM my_table WHERE some_other_column = “something” in SQL

下面是我的SQL表。 我正在嘗試獲取time的最大值,其中to_addressdfhuih

我努力了:

SELECT MAX(time) as max_time FROM transactions WHERE to_address='dfhuih'

但是,該查詢的結果給出了表中的最大time值,而與to_address -使用PHP mysqli時。

在指定to_address time列中選擇最大值的正確方法是什么?

transactions
 ---------------------------------------
| to_address |     time     |  amount  |
----------------------------------------
|  dfhuih    | 1536294884   |  0.320   |
|  dfhuih    | 1536343222   |  0.564   |
|  adslsd    | 1546294884   |  0.320   |
|  vshjfof   | 1536294884   |  0.320   |
----------------------------------------

我的應用程序中的完整代碼是

$stmt1 = $db_connection->prepare("SELECT MAX(time) as max_time FROM transactions WHERE to_address=? AND from_address=? AND is_affiliate_payment=0");
$stmt1->bind_param('is', $user_id, $faucet_key);
$stmt1->execute();
$result1 =$stmt1->get_result();

while($row = $result1->fetch_assoc())
{
   echo $row['max_time']    
}

我相信您正在尋找,但是很難說,沒有示例數據和預期結果。

SELECT 
 transactions.*
FROM (
 SELECT 
   MAX(time) AS max_time
 FROM 
  transactions
 WHERE
   to_address = 'dfhuih'
) AS transactions_filter
INNER JOIN 
 transactions  
ON
   transactions_filter.max_time = transactions.time   
 AND  
   transactions.to_address = 'dfhuih'

請記住,如果兩個MAX時間值相同,它也會顯示平局

在MySQL 8中,您也可以將該查詢重寫為以下查詢。
請注意,列別名已作為列名移動到派生表別名。

SELECT 
 transactions.*
FROM (
 SELECT 
   MAX(time)
 FROM 
  transactions
 WHERE
   to_address = 'dfhuih'
) AS transactions_filter(max_time) # <- here is the column alias also defined.
INNER JOIN 
 transactions  
ON
   transactions_filter.max_time = transactions.time   
 AND  
   transactions.to_address = 'dfhuih'

問題出在這兩行:

$stmt1 = $db_connection->prepare("SELECT MAX(time) as max_time 
                                  FROM transactions 
                                  WHERE to_address = ? AND 
                                        from_address = ? AND 
                                        is_affiliate_payment = 0");
$stmt1->bind_param('is', $user_id, $faucet_key);

有兩個? 在您的查詢中。 第一個是to_address ,第二個是from_address 兩者都是字符串。 但是,在您的bind_param()您要求一個整數to_address 因此,代碼應為:

$stmt1 = $db_connection->prepare("SELECT MAX(time) as max_time 
                                  FROM transactions 
                                  WHERE to_address = ? AND 
                                        from_address = ? AND 
                                        is_affiliate_payment = 0");
$stmt1->bind_param('ss', $to_address, $from_address);

請注意,我還更改了其余參數。 $user_id, $faucet_key似乎不正確。 檢查一下!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM