0

我现在正在使用以下查询...

SELECT id, account_number, 
       (SELECT count(*)
        FROM `member_tbl` t2
        WHERE t2.referred_by = t1.account_number
       ) AS total_referred
FROM `member_tbl` t1;

这提供了以下结果......

id - id of memenr
account_number - account number of user
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

请检查mysql小提琴

并且根据mysql fiddle data,查询必须返回以下值...

| id | account_number  | referred_by1  | referred_by2 | referred_by3
+----+-----------------+---------------+--------------+-------------
|  1 | ac203003        | 0             | 0            | 0
+----+-----------------+---------------+--------------+-------------
|  2 | ac203004        | 1             | 1            | 0
+----+-----------------+---------------+--------------+-------------
|  3 | ac203005        | 2             | 1            | 1
+----+-----------------+---------------+--------------+-------------

让我再举一个例子

如果每个成员总是有 10 次推荐,那么...

referred_by1 = 10
referred_by2 = 100
referred_by3 = 1000

我很困惑,我该如何写这个查询?

4

1 回答 1

0

好吧,您可以使用更复杂的查询保持原样。我认为这就是你想要的:

SELECT id, account_number, 
       (SELECT count(*)
        FROM `member_tbl` t2
        WHERE t2.referred_by = t1.account_number
       ) AS total_referred,
       (SELECT count(*)
        FROM `member_tbl` t2 join
              member_tbl t3
              on t3.referred_by = t2.account_number
        WHERE t2.referred_by = t1.account_number
       ) AS refer4ed_by_2,
       (SELECT count(*)
        FROM `member_tbl` t2 join
              member_tbl t3
              on t3.referred_by = t2.account_number join
              member_tbl t4
              on t4.referred_by = t3.account_number
        WHERE t2.referred_by = t1.account_number
       ) AS referred_by_3
FROM `member_tbl` t1;

这与 SQL Fiddle 的“预期”结果不匹配。但是话又说回来,预期的结果甚至没有正确的行数,所以它们看起来不正确。

于 2013-08-12T23:23:41.113 回答