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:
SELECT imageID
FROM ...
JOIN ...
WHERE designID = 100
ORDER BY garmentID = 1 DESC,
colorID = 5 DESC,
sizeID = 10 DESC;
Note that garmentID
, colorID
, and sizeID
are not used as filters in the WHERE
clause. The values are only used in the ORDER BY
expressions.
Test case:
CREATE TABLE designs (designID int, garmentID int, colorID int, sizeID int);
INSERT INTO designs VALUES (100, 1, 1, 1);
INSERT INTO designs VALUES (100, 1, 2, 2);
INSERT INTO designs VALUES (100, 1, 5, 3);
INSERT INTO designs VALUES (100, 1, 5, 10);
INSERT INTO designs VALUES (100, 1, 5, 15);
INSERT INTO designs VALUES (100, 1, 8, 20);
INSERT INTO designs VALUES (100, 2, 5, 10);
INSERT INTO designs VALUES (100, 2, 6, 15);
INSERT INTO designs VALUES (101, 1, 1, 1);
INSERT INTO designs VALUES (101, 2, 1, 1);
Result:
SELECT *
FROM designs
WHERE designID = 100
ORDER BY garmentID = 1 DESC,
colorID = 5 DESC,
sizeID = 10 DESC;
+----------+-----------+---------+--------+
| designID | garmentID | colorID | sizeID |
+----------+-----------+---------+--------+
| 100 | 1 | 5 | 10 |
| 100 | 1 | 5 | 3 |
| 100 | 1 | 5 | 15 |
| 100 | 1 | 1 | 1 |
| 100 | 1 | 2 | 2 |
| 100 | 1 | 8 | 20 |
| 100 | 2 | 5 | 10 |
| 100 | 2 | 6 | 15 |
+----------+-----------+---------+--------+
8 rows in set (0.02 sec)
Note how the row that matches the specified garmentID
, colorID
and sizeID
is first. Failing that, the rows that match garmentID
and colorID
are next. Then the rows that only match garmentID
follow. Then the rest, which only match the designID
filter of the WHERE
clause.
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".