我有一个" transaction_status"表:
id transaction_id status
1 12 0
2 13 0
3 12 -1
4 14 0
5 13 -1
6 15 0
[END OF TABLE]
我需要获取只有status = 0的记录的事务ID。
例如,我正在寻找上表:
id transaction_id status
4 14 0
6 15 0
到目前为止,我正在尝试:
SELECT id, transaction_id, status
FROM transaction_status
WHERE status = 0 OR status = -1
ORDER BY status ASC
GROUP BY txn_id
HAVING status = 0
但没有运气。我的想法已经不多了。有什么想法吗?谢谢!
答案 0 :(得分:1)
对having子句做了一些小改动。
SELECT id, transaction_id, status
FROM transaction_status
WHERE status = 0 OR status = -1
GROUP BY transaction_id
HAVING min(status) = 0
编辑:也删除顺序,因为它没有任何意义
答案 1 :(得分:1)
使用GROUP BY
并在having
子句中检查min
和max
状态为0
。
<强>查询强>
select `transaction_id`
from `your_table_name`
group by`transaction_id`
having min(`status`) = 0 and max(`status`) = 0;
答案 2 :(得分:0)
我认为处理此问题的最简单方法是使用transaction_id
的条件聚合,并计算哪些ID只与其关联的状态为0。在子查询中执行此操作,然后联接回主表以检索所需的完整匹配记录。
SELECT t1.*
FROM transaction_status t1
INNER JOIN
(
SELECT transaction_id
FROM transaction_status
GROUP BY transaction_id
HAVING SUM(CASE WHEN status <> 0 THEN 1 ELSE 0 END) = 0
) t2
ON t1.transaction_id = t2.transaction_id
ORDER BY t1.id DESC