I had this query:
SELECT `name`, floor(max(score)), skill
FROM
(SELECT k.`name`, s.`name` as skill, *long complex formula* as score
FROM `keywords_skills` ks
JOIN keywords k ON k.id = ks.keyword_id
JOIN skills s ON s.id = ks.skill_id
JOIN jobs_keywords jk ON jk.keyword_id = k.id
WHERE job_id = 87293) t1
GROUP BY `name`
ORDER BY `name` asc
obviously i want ‘skill’ to refer the same row as max(score), but I did not know how to make that happen. However, when I add an ORDER BY to the subquery like so:
SELECT `name`, floor(max(score)), skill
FROM
(SELECT k.`name`, s.`name` as skill, *long complex formula* as score
FROM `keywords_skills` ks
JOIN keywords k ON k.id = ks.keyword_id
JOIN skills s ON s.id = ks.skill_id
JOIN jobs_keywords jk ON jk.keyword_id = k.id
WHERE job_id = 87293
ORDER BY score DESC) t1
GROUP BY `name`
ORDER BY `name` asc
everything seems to work great! My question is: have I solved my problem or just implemented an unreliable hack that will haunt me later?
EDIT: perhaps I should have explain more what I was looking for:
Keywords and Skills are in a many-to-many relationship with each other. I am not looking simply for the keyword with the highest score, but the skill with the highest score for each keyword.
I also thought I could use LIMIT 1 somehow (perhaps in a subquery), but so far have not thought of a way to make it happen.
I think you are close with your first one… just add a LIMIT 1 in addition to the order by to put the highest skill first (order by column 3 which is your score formula
— PER REVISED CLARIFICATION…
I’m swapping around the query in hierarchy of the JOB ID in question, then finding ITs skills and keywords instead of the reverse — relying on keyword skills. In the case you want, you WILL need a nested query… Example:
The inner query should ONLY include the keyword id and the maximum score for the keyword — all associated with the one Job_ID in questino. THEN, re-join again, but this time, we no longer need he job_keywords as each K.ID and name description are IN the prequery. Then, just need to re-join to the skills matching the qualifying SCORE.