cards (id,...)
order_cards (card_id, order_id....)
transactions (order_card_id, status, ....)
我想让所有最近7次交易失败的卡
我正在尝试类似的事情
select cards.*,
(
select sum(case tmp1.status when 'fail' then 1 else 0 end) from
(select transactions.status from order_cards
left join transactions on transactions.order_card_id = order_cards.id
where order_cards.card_id = cards.id
order by transactions.id desc limit 7
) as tmp1
) as total_fail
from cards
group by cards.id
having total_fail > 5
遇到此错误
Unknown column 'cards.id' in 'where clause'
具有上述查询的问题是父级ID在第2级子查询中不起作用。 尝试使用具有count的hading子句,但不能与limit一起使用 任何建议,谢谢
已经尝试过
Use column of parent query in subquery of a subquery
MYSQL - Get all records that have more than 1 record for the same id
答案 0 :(得分:0)
这应该有效。
Select c.*, SUM(t.status = 'FAILED') AS failed_txns
from cards c, order_cards oc, transactions t
where t.status='FAILED'
and oc.order_id = t.order_card_id
and c.id = oc.card_id
group by c.id
having failed_txns >= 7
答案 1 :(得分:0)
我认为parent-id
不能在FROM子句的派生表中使用,但仍可以在WHERE子句和子子查询的SELECT列表中访问。因此,在您的情况下,您可以找到card_id的第8个最近的transaction.id(LIMIT 7,1
),然后根据该transaction.id找到SUM()
:(请注意,同一事务中少于8个事务card_id,LIMIT 7,1
将返回NULL,在这种情况下,所有交易都应计入,因此如下:t1.id > IFNULL((...), 0)
):
SELECT c.*
, IFNULL((
SELECT sum(t1.status = 'fail')
FROM order_cards o1
JOIN transactions t1 on t1.order_card_id = o1.id
WHERE o1.card_id = c.id
AND t1.id > IFNULL((
SELECT t2.id
FROM order_cards o2
JOIN transactions t2 on t2.order_card_id = o2.id
WHERE o2.card_id = c.id
ORDER BY t2.id DESC
LIMIT 7,1
), 0)
), 0) as total_fail
FROM cards c
HAVING total_fail > 5
我在自己的服务器的数据库上测试了一个类似的SQL,该SQL正常运行,并且相同的方法可能适用于您的情况。