我有两行的行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的行之间随机排序。
任何想法如何实现这一目标?
答案 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')