Reputation: 21
I have a simple table, for example:
id | name | category
------------------------
1 | banana | 1
2 | orange | 1
3 | fruit | 1
4 | potato | 2
5 | car | 0
I have a lot of special filters that should assign a special score for the list to show. Here is the mechanism for this example:
So in my results I need to have
id | name | category | score
-------------------------------
1 | banana | 1 | 3 ( condition 1+4)
2 | orange | 1 | 3 ( condition 1+4)
3 | fruit | 1 | 2 ( condition 2+4)
4 | potato | 2 | 1 ( condition 3+4)
5 | car | 0 | 0 ( no match)
And finally I want to order the results by score. I can't create new column, because the conditions are selected by user. What will be MySQL query?
Upvotes: 2
Views: 161
Reputation: 79929
You can do this:
SELECT
id,
name,
category,
nameCondition + catCondition AS Score
FROM
(
SELECT
id, name, category,
CASE
WHEN name IN ('banana', 'orange') THEN 2
WHEN name = 'fruit' THEN 1
WHEN name = 'potato' THEN 0
ELSE 0
END AS nameCondition,
CASE
WHEN category > 0 THEN 1
ELSE 0
END AS catCondition
FROM tablename
) AS t;
This will give you:
| ID | NAME | CATEGORY | SCORE |
----------------------------------
| 1 | banana | 1 | 3 |
| 2 | orange | 1 | 3 |
| 3 | fruit | 1 | 2 |
| 4 | potato | 2 | 1 |
| 5 | car | 0 | 0 |
Upvotes: 1
Reputation: 106385
One possible approach:
SELECT id, name, category,
IF(category > 0, 1, 0) +
(CASE name WHEN 'banana' THEN 2
WHEN 'orange' THEN 2
WHEN 'fruit' THEN 1
ELSE 0 END)
AS score
FROM ttt
ORDER BY score DESC
Upvotes: 3