我有2张桌子
MySQL [prueba]> select * from orders;
+----+--------------+---------------+
| pk | order_number | date_modified |
+----+--------------+---------------+
| 1 | 1 | 2019-06-04 |
| 2 | 1 | 2019-06-06 |
| 3 | 1 | 2019-06-08 |
| 4 | 2 | 2019-06-04 |
| 5 | 2 | 2019-06-06 |
| 6 | 2 | 2019-06-08 |
+----+--------------+---------------+
和
MySQL [prueba]> select * from order_payments;
+----------+--------------+--------+
| order_id | payment_date | amount |
+----------+--------------+--------+
| 1 | 2019-06-04 | 5 |
| 1 | 2019-06-04 | 15 |
| 1 | 2019-06-06 | 10 |
| 1 | 2019-06-06 | 10 |
| 2 | 2019-06-07 | 10 |
| 2 | 2019-06-10 | 10 |
| 2 | 2019-06-05 | 10 |
| 2 | 2019-06-08 | 10 |
| 1 | 2019-06-05 | 10 |
| 1 | 2019-06-05 | 10 |
+----------+--------------+--------+
然后我有这样的查询:
set @last_order = 0;
select *,
if(@last_order = order_number, ABS(DATEDIFF(date_modified, @old_date)), 0) diff_days,
@last_order as 'prev_order',
@old_date as 'prev_date',
@last_order:= order_number as 'ig1',
@old_date:= date_modified as 'ig2'
from orders ord
order by ord.order_number asc
输出以下内容:
+----+--------------+---------------+-----------+------------+------------+-----+------------+
| pk | order_number | date_modified | diff_days | prev_order | prev_date | ig1 | ig2 |
+----+--------------+---------------+-----------+------------+------------+-----+------------+
| 1 | 1 | 2019-06-04 | 0 | 0 | 1900-01-01 | 1 | 2019-06-04 |
| 2 | 1 | 2019-06-06 | 2 | 1 | 2019-06-04 | 1 | 2019-06-06 |
| 3 | 1 | 2019-06-08 | 2 | 1 | 2019-06-06 | 1 | 2019-06-08 |
| 4 | 2 | 2019-06-04 | 0 | 1 | 2019-06-08 | 2 | 2019-06-04 |
| 5 | 2 | 2019-06-06 | 2 | 2 | 2019-06-04 | 2 | 2019-06-06 |
| 6 | 2 | 2019-06-08 | 2 | 2 | 2019-06-06 | 2 | 2019-06-08 |
+----+--------------+---------------+-----------+------------+------------+-----+------------+
我现在想做的是知道每个订单修改有多少笔交易。
例如,我想拥有一个名为num_of_transactions的列,该列具有对order_payments的计数,其中order_id = row.order_number和payment_date在row.prev_date和row.date_modified之间。
最终所需的输出(清除不必要的列之后):
+----+--------------+---------------+-----------+------------+------------+
| pk | order_number | date_modified | diff_days | payments | prev_date |
+----+--------------+---------------+-----------+------------+------------+
| 1 | 1 | 2019-06-04 | 0 | 0 | 1900-01-01 |
| 2 | 1 | 2019-06-06 | 2 | 4 | 2019-06-04 |
| 3 | 1 | 2019-06-08 | 2 | 2 | 2019-06-06 |
| 4 | 2 | 2019-06-04 | 0 | 0 | 2019-06-08 |
| 5 | 2 | 2019-06-06 | 2 | 1 | 2019-06-04 |
| 6 | 2 | 2019-06-08 | 2 | 1 | 2019-06-06 |
+----+--------------+---------------+-----------+------------+------------+