我有这样一张桌子:
// financial_supporter
+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
| 1 | 342 | 1000 |
| 2 | 234 | 6500 |
| 3 | 675 | 500 |
| 4 | 342 | 500 |
| 5 | 89 | 800 |
| 6 | 234 | 1500 |
| 7 | 342 | 1200 |
+----+---------+--------+
我需要选择上面的所有列以及另一个名为“for_the_n_time
”的列。它应该包含用户支持我们的次数。
所以预期的结果是:
// financial_supporter
+----+---------+--------+----------------+
| id | user_id | amount | for_the_n_time |
+----+---------+--------+----------------+
| 1 | 342 | 1000 | 3 | -- for the third time
| 2 | 234 | 6500 | 2 | -- for the second time
| 3 | 675 | 500 | 1 | -- for the first time
| 4 | 342 | 500 | 2 | -- for the second time
| 5 | 89 | 800 | 1 | -- for the first time
| 6 | 234 | 1500 | 1 | -- for the first time
| 7 | 342 | 1200 | 1 | -- for the first time
+----+---------+--------+----------------+
这是我的查询不完整。我想我需要一个自我加入,但我不能完全实现。
SELECT fs.*, <I don't know> as for_the_n_time
FROM financial_supporter fs
INNER JOIN financial_supporter as fs2 ON <I don't know>
WHERE 1
ORDER BY id DESC
知道我该怎么办?
编辑:另外我怎么能像这样做DESC命令:
// financial_supporter
+----+---------+--------+----------------+
| id | user_id | amount | for_the_n_time |
+----+---------+--------+----------------+
| 7 | 342 | 1200 | 3 | -- for the third time
| 6 | 234 | 1500 | 2 | -- for the second time
| 5 | 89 | 800 | 1 | -- for the first time
| 4 | 342 | 500 | 2 | -- for the second time
| 3 | 675 | 500 | 1 | -- for the first time
| 2 | 234 | 6500 | 1 | -- for the first time
| 1 | 342 | 1000 | 1 | -- for the first time
+----+---------+--------+----------------+
您可以使用相关子查询计算生成的列。我假设记录的日期与id
列相关,即早期的贡献将比后来的贡献具有更低的id
。
SELECT *,
(SELECT COUNT(*) FROM financial_supporter fs2
WHERE fs1.user_id = fs2.user_id AND fs2.id <= fs1.id) for_the_n_time
FROM financial_supporter fs1
ORDER BY id DESC;