I have a problem with selecting alternating rows in mysql - Image:
CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`file` varchar(255) DEFAULT NULL,
`project_id` int(10) unsigned DEFAULT NULL,
);
And want to be able to select rows from images table in such a way as to have alternating values of project_id IS NOT NULL. Basically:
- image with project_id
- image without project_id
- image with project_id
- image without project_id
- image with project_id
- image without project_id
How can this be accomplished in one SQL query? I've tried:
SELECT `images`.*,
IF(images.project_id, images.project_id % 2, images.id % 2) AS `mixer`
FROM `images` AS `images`
ORDER BY `mixer` DESC
But it's not what I need. Also the final query will probably have a "GROUP BY images.id" in it so if the solution does not mess up the query that would be quite welcome.
Interesting challenge. Try this:
This works by incrementing one of two values
@x
and@y
based on the condition and having the value you want ordered first start with a lower initial value. The result of the evaluation is in the range1, 2, 3, 4, ...
as can be seen from running: