With a PHP code, I wish to order some MySQL results in a specific way.
I have two tables:
First table, called "post" with the following non-exhaustive content:
- id
- released_date
- published_date
- ...
Second table, called "votes" with the following non-exhaustive content:
- id
- post_id
- user_id
- status
If a user votes for an existing post, a record is made in the "votes" table, inserting the post id as post_id and the user id as user_id. The status is 1 for an upvote and 2 for a downvote.
One important thing to keep in mind though: some posts might never receive any vote at all, and 0 occurrence would be found in the second table, for instance!
So, now on my first page I order my posts with their amount of votes (upvotes-downvotes) the following way, and it works fine:
$post_req = mysql_query('SELECT * FROM post
WHERE NOW() > released_date
ORDER BY ((SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 1)-(SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 2)) DESC, published_date DESC
LIMIT 0, 5');
But on the next page (i.e a new iteration), I need to continue where I left, in terms of votes. Before I do that, I save the votes amount of the last post of the first page to pass it to the next one, under the variable $last_post_votes.
Now, this where I struggle: I need to look for posts which have a lower amount of votes than this variable in a new request. As follows, my failing attempt:
$post_req_1 = mysql_query('SELECT * FROM post
WHERE NOW() > released_date
AND ((SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 1)-(SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 2)) < "'.$last_post_votes.'"
ORDER BY ((SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 1)-(SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 2)) DESC, published_date DESC
LIMIT 5');
And then I tried something like that, which failed too:
$post_req_1 = mysql_query('SELECT post.*,
((SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 1)-(SELECT COUNT(*) FROM votes WHERE votes.poste_id = post.id AND votes.status = 2)) AS all_votes
FROM post, votes
WHERE NOW() > post.released_date
AND all_votes < "'.$last_post_votes.'"
ORDER BY all_votes DESC, post.published_date DESC
LIMIT 5');
The problem is clearly the condition upon searching results from another table in the SELECT.
Any help is greatly appreciated!
Thanks a lot in advance! :-)
Lois
EDIT:
I managed to make it work as I wished, by using a condition directly in the ORDER BY
itself. Not sure it's super proper, but it seems to work:
$post_req_1 = mysql_query('SELECT * FROM post
WHERE NOW() > released_date
ORDER BY ((SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 1)-(SELECT COUNT(*) FROM votes WHERE votes.post_id = post.id AND votes.status = 2)) < "'.$last_post_votes_passed.'" DESC, published_date DESC
LIMIT 5');