【问题标题】:MySQL SELECT MAX() queryMySQL SELECT MAX() 查询
【发布时间】:2017-10-28 13:48:29
【问题描述】:

我有一个交易表,我在其中插入交易并保存每笔交易的当前总额(或余额)。我的表如下所示: 事务表

这里,

  • 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 的每个朋友的最新当前总数。上表中的 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')

【问题讨论】:

    标签: android mysql max


    【解决方案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
    

    【讨论】:

    • 我认为这是检索每个 user_id_2 的最大值(current_total)。我希望它为每个 user_id_2 检索与 max(transaction_id) 关联的当前总数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多