I’m working on a search feature and need help with a complex sorting requirement. I have ads that need to be sorted by their active date, but there’s a special case. Most ads should be sorted normally by date, but ads with categoryID=7 need to appear at the bottom of the results even if they have newer dates.
Basically I want regular ads (categoryID != 7) sorted by date first, then all categoryID=7 ads sorted by date but always appearing after the regular ones.
Here’s my current query that works for normal sorting but doesn’t handle the special case:
SELECT
listings.listingID,
listingText,
listingActiveDate,
categoryID,
locations.locationName,
listing_photos.photoPath
FROM listings
LEFT JOIN locations ON listings.locationID = locations.locationID
LEFT JOIN listing_photos ON listing_photos.photoDefault = 1 AND listing_photos.listingID = listings.listingID AND listing_photos.photoPath != ''
WHERE
listings.listingType = 0
AND listings.listingSold = 0
AND listings.listingID IN
(
SELECT DISTINCT listings.listingID
FROM listings
LEFT JOIN listings_featured ON listings_featured.listingID = listings.listingID
WHERE listings.listingActive = 1
)
ORDER BY categoryID, listings.listingActiveDate DESC
I could run two separate queries and combine them in PHP but the current code structure requires a single query. Is there a way to achieve this custom sorting in one MySQL query?
The desired output should show regular ads first (sorted by date), then categoryID=7 ads at the bottom (also sorted by date):
ID | Text | ActiveDate | categoryID | locationName | photoPath
___________________________________________________________________________
1 | Item Text | 2010-06-01 | 3 | TX | pic.jpg
4 | Item Text | 2010-05-31 | 2 | FL | pic1.jpg
8 | Item Text | 2010-03-01 | 4 | TX | pic3.jpg
5 | Item Text | 2010-06-01 | 7 | TX | pic5.jpg
7 | Item Text | 2010-05-01 | 7 | TX | pic7.jpg
Any suggestions would be really helpful!