
Originally Posted by
r937
the following handles wraparound and does not assume that the lowest order is 1
Code:
$current_order = 2;
$query = "
SELECT `id`
, `order`
FROM `table`
WHERE `order` =
( SELECT MIN(`order`)
FROM `table`
WHERE `order` > " . $current_order . " )
UNION ALL
SELECT `id`
, `order`
FROM `table`
WHERE `order` =
( SELECT MIN(`order`)
FROM `table` )
ORDER
BY `order` DESC LIMIT 1"
@r937
I ran some tests here and it's very clever how you used the MIN() there 
My resulting query is done and working well and contains some dynamic values of course.
Code:
SELECT a.id, za.order, za.zone_id
FROM wp_wpbrads AS a
LEFT JOIN wp_wpbrzonesads AS za
ON a.id = za.ad_id
WHERE za.order =
(SELECT MIN(za.order)
FROM wp_wpbrzonesads AS za
WHERE za.order > 2
AND za.zone_id = 2
AND a.active = 'Y'
AND (a.expiry = '0000-00-00' OR a.expiry >= '2012-11-07')
AND (a.startDate = '0000-00-00' OR a.startDate <= '2012-11-07')
AND (a.impressions = 0 OR a.impressions <= a.views) AND a.id != '1')
UNION ALL
SELECT a.id, za.order, za.zone_id
FROM wp_wpbrads AS a
LEFT JOIN wp_wpbrzonesads AS za
ON a.id = za.ad_id
WHERE za.order =
(SELECT MIN(za.order)
FROM wp_wpbrzonesads AS za
WHERE za.zone_id = 2 AND a.active = 'Y'
AND (a.expiry = '0000-00-00' OR a.expiry >= '2012-11-07')
AND (a.startDate = '0000-00-00' OR a.startDate <= '2012-11-07')
AND (a.impressions = 0 OR a.impressions <= a.views) AND a.id != '1')
ORDER BY `order` DESC LIMIT 1;
Bookmarks