我有一个这样的表(MySQL 5.0.x,MyISAM):
user{id, login, ip, banned} (Banned: 0 false, 1 true)
如果至少有5个具有相同IP的其他用户已被禁止(banned=0
),我希望找到所有未被禁止的用户(banned=1
)。
感谢您的帮助! :)
答案 0 :(得分:4)
如果您有很多被禁用的用户:
SELECT *
FROM user uo
WHERE EXISTS (
SELECT 1
FROM user ui
WHERE ui.ip = uo.ip
AND banned = 1
LIMIT 4, 1
)
AND banned = 0
如果您禁用的用户很少:
SELECT *
FROM user
WHERE ip IN (
SELECT ip
FROM user
WHERE banned = 1
GROUP BY
ip
HAVING COUNT(*) >= 5
)
AND banned = 0
在这两种情况下,在(ip, banned)
上建立索引会大大改善这些查询。
答案 1 :(得分:1)
SELECT id
FROM user
WHERE ip IN (
SELECT DISTINCT ip
FROM user
WHERE COUNT(*) >= 5
AND banned = 1
GROUP BY ip
)
AND banned = 0