Here's a simplified version of a table I have:
sometable
title | tag | score
-----------------------
foo1 bar 100
bar2 oobar 50
meh3 25
Currently, If I want to开发者_C百科 search the table and have oo
be my search query, I'd execute something like:
SELECT *, (title||" "||tag) AS titletag
FROM sometable WHERE titletag LIKE "%oo%"
ORDER BY score DESC
and the above would return the foo1
row first, and bar2
second.
What I'd like to add in, is if the search query (oo
) matches the start of a tag
(eg tag LIKE "oo%"
), I want said rows to come first before any other row, regardless of score, but still retain the rest of the original query.
So by searching for oo
, I'd want the bar2
row returned first since oo
matches the start of oobar
, and then have foo1
come second, even though bar2
's score is lower than foo1
's.
How can I achieve this?
Try to use Union
:
SELECT *, (title||" "||tag) AS titletag
FROM sometable WHERE titletag LIKE "oo%"
UNION
SELECT *, (title||" "||tag) AS titletag
FROM sometable WHERE titletag LIKE "%oo%"
ORDER BY score DESC
But you should be aware of Maximum Number Of Terms In A Compound SELECT Statement
VMAtm's answer didn't quite work but gave me an idea to use:
SELECT *, (title||" "||tag) AS titletag, score*100 AS newscore
FROM sometable WHERE tag LIKE "oo%"
UNION
SELECT *, (title||" "||tag) AS titletag, score AS newscore
FROM sometable WHERE titletag LIKE "%oo%"
ORDER BY newscore DESC
This way, in the first SELECT
term, matching tag
s are assigned a much higher score, and in the second SELECT
term their scores stay the same.
So bar2
would come first with a newscore
of 5000, and foo1
comes second because its newscore
stays at 100.
精彩评论