I've read many answers to this question but none seem to answer in the scenario when you need to pick one random row in a DB of articles, say a wordpress db, where in the wp_posts, you actually have both revisions, trashed and published articles.
Previous answers seems to return blank result if the id is random and the post is not published like in this code
SELECT * FROM wp_posts AS w
JOIN (SELECT (RAND() * (SELECT MAX(id) FROM wp_posts)) AS id) AS r2
WHERE w.id >= r2.id
AND w.post_status = 'publish'
ORDER BY w.id ASC
LIMIT 1
Just use
SELECT *
FROM wp_posts
WHERE post_status = 'publish'
ORDER BY RAND()
LIMIT 1
to get a random record being published.
Your method is intended to be more efficient than sorting all the published articles. The following is similar for only published articles:
SELECT *
FROM wp_postsw CROSS JOIN
(SELECT (RAND() * (SELECT MAX(id) FROM wp_posts WHERE post_status = 'publish')) AS id
) r2
WHERE w.id >= r2.id AND w.post_status = 'publish'
ORDER BY w.id ASC
LIMIT 1;
For performance, you want an index on wp_posts(post_status, id)
.
That is, you need the condition inside the subquery. And, you need to include the appropriate columns in the WHERE
clause.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.