我正在使用以下查询,这真的很慢(大约需要 30-45 分钟)并且有时会卡住,并生成 500 错误,这对应用程序不利...
SELECT id, account_number, email, referred_by, dnt,
(SELECT count(*)
FROM tbl.registrations t2
WHERE t2.referred_by = t1.account_number
) AS level1,
(SELECT count(*)
FROM tbl.registrations t2 join
tbl.registrations t3
on t3.referred_by = t2.account_number
WHERE t2.referred_by = t1.account_number
) AS level2,
(SELECT count(*)
FROM tbl.registrations t2 join
tbl.registrations t3
on t3.referred_by = t2.account_number join
tbl.registrations t4
on t4.referred_by = t3.account_number
WHERE t2.referred_by = t1.account_number
) AS level3
FROM tbl.registrations t1 GROUP BY id;
我们在这个表中有大约 35000 行,数据库结构如下......
| id | account_number | referred_by |
+----+-----------------+--------------+
| 1 | ac01 | 5 |
+----+-----------------+--------------+
| 2 | ac02 | 5 |
+----+-----------------+--------------+
| 3 | ac03 | 4 |
+----+-----------------+--------------+
level1、level2、level3的计算如下...
total_referred - total number of members referred by account_number
total_reffered2 - total number of members that THEY(all accounts referred by account_number) all referred
total_reffered3 - total number of members that referred by all members of total_reffered2
例如
如果每个成员总是有 10 次推荐,那么...
level1 = 10
level2 = 100
level3 = 1000
请检查我做错了什么?请帮我重写这个查询或优化,顺便说一句我已经尝试添加索引。谢谢