sql - 从2个表中选择

时间:2017-07-20 19:34:40

标签: sql

我有一个表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

1 个答案:

答案 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;