here’s my problem.
I have a website with a database of books which can be searched using pre-defined keywords. In the database, for each book, we can add max 20 different keywords to a book (like “management”, “leadership”, etc.), with a relevance value for each keyword (from 1 to 5). At this time, when choosing a specific keyword, I’m able to sort all books which have that keyword stored as a theme.
In the database, we have 1 field per keyword and 1 field per value, so 40 fields for 20 keywords.
My problem is that the books are sorted in a strange way based on the order the keywords were added to the book (from first to 20th), the relevance value being taken in account only field by field (first keyword with first, etc.).
What I would like is to be able to sort them like this: first, the books with a keyword value of 5, then 4, etc. to 1, no matter if it’s the first or last keyword added for the book. Actually, it would really mean “by relevance”.
I tried to use “ORDER BY CONCAT”, but it didn’t change anything.
Here is an example of query with a specific keyword:
SELECT *,
IF(id_theme_1=13,id_theme_deg_1,0) AS isInDeg_1,
IF(id_theme_2=13,id_theme_deg_2,0) AS isInDeg_2,
IF(id_theme_3=13,id_theme_deg_3,0) AS isInDeg_3,
IF(id_theme_4=13,id_theme_deg_4,0) AS isInDeg_4,
IF(id_theme_5=13,id_theme_deg_5,0) AS isInDeg_5,
IF(id_theme_6=13,id_theme_deg_6,0) AS isInDeg_6,
IF(id_theme_7=13,id_theme_deg_7,0) AS isInDeg_7,
IF(id_theme_8=13,id_theme_deg_8,0) AS isInDeg_8,
IF(id_theme_9=13,id_theme_deg_9,0) AS isInDeg_9,
IF(id_theme_10=13,id_theme_deg_10,0) AS isInDeg_10,
IF(id_theme_11=13,id_theme_deg_11,0) AS isInDeg_11,
IF(id_theme_12=13,id_theme_deg_12,0) AS isInDeg_12,
IF(id_theme_13=13,id_theme_deg_13,0) AS isInDeg_13,
IF(id_theme_14=13,id_theme_deg_14,0) AS isInDeg_14,
IF(id_theme_15=13,id_theme_deg_15,0) AS isInDeg_15,
IF(id_theme_16=13,id_theme_deg_16,0) AS isInDeg_16,
IF(id_theme_17=13,id_theme_deg_17,0) AS isInDeg_17,
IF(id_theme_18=13,id_theme_deg_18,0) AS isInDeg_18,
IF(id_theme_19=13,id_theme_deg_19,0) AS isInDeg_19,
IF(id_theme_20=13,id_theme_deg_20,0) AS isInDeg_20
FROM mng_ouvrages
WHERE lang='fr' AND publish=1
ORDER BY CONCAT(isInDeg_4,isInDeg_2,isInDeg_3,isInDeg_1,isInDeg_5,isInDeg_6,isInDeg_7,isInDeg_8,isInDeg_9,isInDeg_10,
isInDeg_11,isInDeg_12,isInDeg_13,isInDeg_14,isInDeg_15,isInDeg_16,isInDeg_17,isInDeg_18,isInDeg_19,isInDeg_20) DESC
With this, I’m first getting books with the keyword stored in the 4th field (with a relevance of 3), before books with the keyword stored in the 1st field (with a relevance of 5).
Does anyone know if there’s a way to do this kind of sorting?
Many thanks for your help.
You can use MySQL’s
GREATEST()function to get the maximum relevance value over all keywords: