让我说我有事务表,它有transaction_date,我想知道我的许多交易是如何在每个交易中发生的,不包括已取消的交易。
查询示例
SELECT transaction_id, transaction_status,
(SELECT COUNT(*) FROM transaction WHERE user_id = 2
AND transaction_date BETWEEN DATE_FORMAT(transaction_date, '%Y-%m-01 00:00:00')
AND transaction_date AND transaction_status != 'cancel') AS transaction_counter
FROM transaction WHERE user_id = 2
Result:
-------------------------------------------------------------
| transaction_id | transaction_status | transaction_counter |
-------------------------------------------------------------
| 1 | success | 1 |
| 2 | cancel | 1 |
| 3 | success | 2 |
| 4 | success | 3 |
| 5 | success | 4 |
| 6 | cancel | 4 |
-------------------------------------------------------------
但是这个查询运行速度非常慢,因为它计算每一行,并且需要5-10分钟才能进行一千次交易。有没有想过优化这个查询?