可以以某種方式連接表並避免在以下MySQL查詢中使用distinct。 invited_by_id顯示邀請此用戶的用戶的用戶標識。如何優化嵌套查詢?
SELECT
user1.id, count(distinct user2.id) AS theCount, count(distinct user3.id) AS theCount2
FROM
users AS user1
LEFT OUTER JOIN
users AS user2 ON user2.invited_by_id=user1.id
LEFT OUTER JOIN (
SELECT id, invited_by_id FROM users WHERE signup_date >= NOW() - INTERVAL 30 DAY
) AS user3 ON user3.invited_by_id=user1.id
GROUP BY user1.id;
爲什麼你需要獨特?在我看來,用戶X只能被用戶Y *一次*邀請。 – 2010-01-29 08:49:59
@Lieven由於表格被連接兩次,所以你可以得到重複的行。 – 2010-01-29 17:22:25