【发布时间】: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