MYSQL find related query
I'm writing a query where I'm looking to pull related fields from a database with a limit of 10 rows.
The query is easy to write, however I was wondering if there is a way to write the query so it searches for related items开发者_运维问答 and pulls those first and if those are < 10 it will just pull random fields for the remaining ones.
Here is the query I use to pull the related rows
SELECT * FROM table WHERE term LIKE '%term1%' or term LIKE '%term2%' LIMIT 0,10
Your just need to order the table by the terms that you are looking for first, one way of doing this is as follows:
SELECT * FROM table
ORDER BY (
(
CASE WHEN term LIKE '%term1%'
THEN 1
ELSE 0
END
) + (
CASE WHEN term LIKE '%term2%'
THEN 1
ELSE 0
END
)
) DESC
LIMIT 0,10
精彩评论