android - MySQL SELECT MAX() 查询

标签 android mysql max

我有一个交易表,我可以在其中插入交易,并保存每笔交易的当前总额(或余额)。我的 table 看起来像这样: 交易表

enter image description here

这里,

  • transaction_id 是唯一主键
  • user_id_1 是我的 PHP 文件通过 POST 收到的 user_id
  • user_id_2 是与 user_id_1 进行过交易的好友 ID
  • transaction_code 为 0 表示收款(减少 current_total),1 表示付款(增加 current_total)
  • transaction_status 1 表示交易已确认

我想使用选择操作检索给定 user_id 的每个 friend 的最新当前总数。上表中 user_id_1 = '26' 的情况如下:

user_id_2 current_total
1         375  
27        350

到目前为止,我已经想出了这个,但它没有按预期工作:

select user_id_2, current_total from transactiontable where user_id_1 = '$user_id' and (transaction_id=(SELECT MAX(transaction_id)) and transaction_status = '1')

最佳答案

您可以使用 GROUP BY 子句查找最高 ID,然后将其与原始表连接

类似这样的事情:

SELECT user_id_2, current_total 
    FROM transactiontable 
    INNER JOIN (
        SELECT MAX(transaction_id) AS maxID 
        FROM transactiontable 
        WHERE user_id_1 = '26' 
        AND transaction_status = '1' GROUP BY user_id_2 
    ) AS m 
    ON transaction_id=maxID

关于android - MySQL SELECT MAX() 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46986468/

相关文章:

php - mysql重音不敏感和点不敏感搜索

c++ - 如何在没有 if 语句的情况下从最小到最大对一组整数进行排序?

android - 设置、应用程序和运行下有 0 个进程和 1 个服务

java.lang.RuntimeException : Unable to start activity ComponentInfo(Program crashes when started) 错误

java - 在按钮逻辑中尝试捕捉

php - 如何在时间格式之间进行转换?

mysql - Grails 2.4.3 & MySQL & grails.project.fork = false

javascript - 在稀疏 javascript 数组中查找最大值

java - 如何编写一个接受 int 变量并返回最大变量的方法?

android - 除非首先连接到 WIFI 网络,否则 FusedLocationProviderClient 无法通过 3G 或 4G 网络获取 GPS 位置