我有一个表users
和表questions
。我想从users
表中选择5个随机用户,这些用户在questions
表中至少有20个查询(db.questions to_user = db.users id)。我所有人都尝试过:
SELECT *
FROM users s
WHERE exists (SELECT 20
FROM questions m
WHERE m.to_user = s.id)
ORDER BY RAND()
LIMIT 5
答案 0 :(得分:2)
我认为这更符合您的要求:
SELECT u.*
FROM users u
WHERE (SELECT COUNT(*) FROM questions q WHERE q.to_user = u.id) >= 20
ORDER BY RAND()
LIMIT 5;