【问题标题】:Get right row values retrieved with "group by" [duplicate]使用“group by”获取正确的行值 [重复]
【发布时间】:2019-04-02 10:16:16
【问题描述】:

我们有“交易”表:

id  amount  txn_id  status  status_text
1    15     123456     0      pending
2    11     123123     0      pending
3    15     123456     1      complete
4    20     321456     0      pending
5    17     987456     0      pending
6    25     321321     0      pending
7    20     321456     1      complete
8    25     321321     1      complete

我们需要为每个事务 id (txn_id) 获取具有最高状态的行。我们正在使用这个查询:

SELECT id, amount, txn_id, status, status_text, MAX(status) as max_status 
FROM transactions  
GROUP BY txn_id 
ORDER BY id DESC

我们期待:

id  amount  txn_id  status  status_text  max_status
8    25     321321     1      complete       1
7    20     321456     1      complete       1
5    17     987456     0      pending        0
3    15     123456     1      complete       1
2    11     123123     0      pending        0

但除了“status_text”和“status”列似乎是随机的之外,我们一切正常。 “max_status”是正确的。

id  amount  txn_id  status  status_text  max_status
8    25     321321     1      complete       1
7    20     321456     0      pending        1
5    17     987456     0      pending        0
3    15     123456     0      complete       1
2    11     123123     0      pending        0

我的想法不多了。 我们如何获取每个事务 id 的最高状态的行?

谢谢!

【问题讨论】:

  • 如果您在 MySQL 中打开了严格模式,那么您会看到查询失败。因为您选择了既不分组也不聚合的列,这就是您遇到问题的原因。
  • 你的 MySQL 服务器版本是多少?
  • @madhur 可能低于 5.8,以上查询在较新版本中默认无效。

标签: php mysql mysqli mysql-workbench mysql-python


【解决方案1】:

您可以在下面使用子查询尝试

select a.id,a.amount,a.txn_id, a.`status`, status_text,mstatus from transaction a
inner join
(
select txn_id,max(`status`) as mstatus
from transaction group by txn_id
)b on a.txn_id=b.txn_id and a.`status`=b.mstatus

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    相关资源
    最近更新 更多