问题
I currently have a PHP function (codeigniter) which takes a query string (from post), and returns relevant MySQL rows, like this:
$term = $this->input->post("query");
$rows = $this->db->query("SELECT id, title as 'desc' , abbreviation , etc FROM shows WHERE abbreviation LIKE '%".$term."%' OR title LIKE '%".$term."%' OR etc LIKE '%".$term."%' LIMIT 10; ")->result_array();
this works, but lets say my table is like this :
id title abbreviation
-- ---------------------- ------------
1 The Big Bang Theory TBBT
2 How I Met Your Mother HMYM
3 a show called tbbt hmym ASCTM
Now, when the user searches for tbbt
, it returns 3rd row first. But I want the abbreviation to be the "main" parameter.
So if abbreviation matches, return it first, then look for the title column.
I think I can do it with PHP, like this:
// pseudo-code :
$abbreviation_matches = result("bla bla WHERE abbreviation LIKE term AND NOT title like term");
$title_matches = result("bla bla WHERE NOT abbreviation LIKE term AND title LIKE term");
$result = append($abbreviation_matches , $title_matches);
But I'm afraid this will not be so efficient, since it involves 2 separate SQL queries. So is there a more efficient way to do this? Preferrably in one query ?
And the real case is with 4 columns, but only one column has priority, so the other ones are not important in order.
Thanks for any help!
回答1:
It could be one of the solutions:
SELECT id, desc, abbreviation, etc FROM
(
SELECT 1 AS rnk, id, title as 'desc' , abbreviation , etc FROM shows
WHERE abbreviation LIKE '%".$term."%'
UNION
SELECT 2 AS rnk, id, title as 'desc' , abbreviation , etc FROM shows
WHERE title LIKE '%".$term."%'
) tab
ORDER BY rnk
LIMIT 10;
Or you can achieve the same by the following:
SELECT id, desc, abbreviation, etc FROM
(
SELECT CASE WHEN abbreviation LIKE '%".$term."%' THEN 1 ELSE 2 END As rnk,
id, title AS desc, abbreviation, etc
FROM shows
WHERE abbreviation LIKE '%".$term."%'
OR title LIKE '%".$term."%'
) tab
ORDER BY rnk
LIMIT 10;
来源:https://stackoverflow.com/questions/21995743/how-to-search-multiple-columns-with-priority-in-mysql