PHP Mysql从两个ID中选择随机行?

时间:2014-06-29 09:10:42

标签: php mysql

我有两行的行ID,我如何在我的查询中随机两行?

到目前为止我的查询:

SELECT * 
FROM `users` 
WHERE user_id = '1' 
    AND active = '1' 
    AND id = '100' 
    OR id = '200' 
ORDER BY RAND() LIMIT 1

所以我想做的是在id为100且id为200的行之间随机排序。

任何想法如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

您需要围绕OR条件的括号:

SELECT * 
FROM `users` 
WHERE user_id = '1' 
    AND active = '1' 
    AND (id = '100' OR id = '200')
ORDER BY RAND() LIMIT 1

OR的优先级低于AND,因此您的WHERE子句被解释为

WHERE (user_id = '1' 
        AND active = '1' 
        AND id = '100')
    OR id = '200')

更好的方法是使用IN

WHERE user_id = '1' 
    AND active = '1' 
    AND id IN ('100', '200')