我创建了一个可以与推荐系统一起使用的新系统, 但是如何获得有关推荐人数最多的用户的信息呢?
我认为SQL命令是这样的:
select * from user where refered_user=max(count(user.refered_user));
正确的符号是什么?
答案 0 :(得分:1)
我认为你的用户表看起来像:
TABLE: user
COLUMN: id int PK
COLUMN: refered_user int FK ON user.id
编辑:删除了HAVING子句并添加了子查询
不使用HAVING查找最大引荐数,我添加了一个新的子查询来查找:
SELECT MAX(referals)
FROM (
SELECT refered_user, COUNT(1) referals
FROM user
GROUP BY refered_user
)
然后,我在查询中使用了这个来获取多次引用的用户:
SELECT refered_user, referals
FROM (
SELECT refered_user, COUNT(1) referals
FROM user
WHERE refered_user IS NOT NULL
GROUP BY refered_user
) AS ruser
WHERE referals = (
SELECT MAX(referals)
FROM (
SELECT refered_user, COUNT(1) referals
FROM user
WHERE refered_user IS NOT NULL
GROUP BY refered_user
) AS muser
)
最后,我使用它作为JOIN查询:
SELECT u.*
FROM user u
INNER JOIN (
SELECT refered_user, referals
FROM (
SELECT refered_user, COUNT(1) referals
FROM user
WHERE refered_user IS NOT NULL
GROUP BY refered_user
) AS ruser
WHERE referals = (
SELECT MAX(referals)
FROM (
SELECT refered_user, COUNT(1) referals
FROM user
WHERE refered_user IS NOT NULL
GROUP BY refered_user
) AS muser
)
) AS r ON (r.refered_user = u.id)
结束修改
请注意,由于多个用户可以拥有相同(最大)的引荐数,因此此查询可以返回0(对于空表),1行或更多行。