下面是我的SQL表。我正在尝试获取time
的最大值,其中to_address
是dfhuih
。
我尝试过:
SELECT MAX(time) as max_time FROM transactions WHERE to_address='dfhuih'
但是,使用PHP mysqli时,该查询的结果在表中给出最大的time
值,而与to_address
无关。
在我的time
列(其中指定了to_address
)中选择最大值的正确方法是什么?
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']
}
答案 0 :(得分:1)
我相信您正在寻找,但是很难在没有示例数据和预期结果的情况下使用。
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'
答案 1 :(得分:1)
问题出在这两行:
$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
似乎不正确。检查一下!