I have several tables that get JOINed together to form a table with columns
designID
garmentID
colorID
sizeID
imageID
I have a function that looks like this [variables in square brackets are optional]:
getProductImages($designID, [$garmentID], [$colorID], [$sizeID]);
I want it to return all imageIDs that match $designID in the following order:
- Rows that match $garmentID, $colorID, and $sizeID first
- Rows that match $garmentID and $colorID next
- Rows that match just $garmentID next
- Rows that match none (just $designID) last
I could do this pretty easily by just loading all the rows that match $designID and then sorting them in PHP, but my understanding is that it’s generally faster to do sorting in MySQL when possible. There will be about 20 rows matching a given $designID.
So my question is twofold: Is it worth doing the sorting in a SQL statement? If I do, what is the best approach to take?
I would also be very interested to know if there is a name for this kind of sorting.
If I understood correctly, it looks like you can use expressions in your
ORDER BY, in a way similar to the accepted answer given to the following Stack Overflow post:Therefore, your query might look like this:
Note that
garmentID,colorID, andsizeIDare not used as filters in theWHEREclause. The values are only used in theORDER BYexpressions.Test case:
Result:
Note how the row that matches the specified
garmentID,colorIDandsizeIDis first. Failing that, the rows that matchgarmentIDandcolorIDare next. Then the rows that only matchgarmentIDfollow. Then the rest, which only match thedesignIDfilter of theWHEREclause.I believe it is worth doing this in SQL. As @Toby noted in the other answer, in general you don’t need to worry about performance when sorting such a small number of rows, assuming you will always be filtering by
designID… As for your other question, I don’t know if there is a name for such a query – I tend to call it “ordering by an expression”.