所以我有一个包含2列的表
class_id | title
CS124 | computer tactics
CS101 | intro to computers
MATH157 | math stuff
CS234 | other CS stuff
FRENCH50 | TATICS of french
ENGR101 | engineering ETHICS
OTHER1 | other CS title
我希望在用户搜索某些内容时进行自动完成的智能搜索。
让我们说他们输入CS'在框中我想使用class_id
和title
进行搜索,限制为5,对于此示例。我首先要搜索类似于' CS%'的class_ids。由class_id排序的限制为5。这将返回3 cs类。
然后,如果在限制中还剩下任何空间,我想使用'%CS%之类的标题进行搜索并合并它们,但首先要保留class_id
个匹配项,并确保从中删除重复项底部就像cs234一样,在两个查询中都匹配。
因此该查询的最终结果是
CS101 | intro to computers
CS124 | computer tactics
CS234 | other CS stuff
ENGR101 | engineering ETHICS
FRENCH50 | TATICS of french
我正在尝试做这样的事情
(select * from class_infos
where LOWER(class_id) like LOWER('CS%')
order by class_id)
union
(select * from class_infos
where LOWER(title) like LOWER('%CS%')
order by class_id)
limit 30
但它并没有按照正确的顺序排列它们,或者使class id
查询具有优先权。任何人都有任何建议
这是sqlfiddle http://sqlfiddle.com/#!15/5368b
答案 0 :(得分:1)
你试过这样的事吗?
SELECT *
FROM
(
(select 1 as priority, *
from class_infos
where LOWER(class_id) like LOWER('CS%'))
union
(select 2 as priority, *
from class_infos
where
LOWER(title) like LOWER('%CS%')
and not LOWER(class_id) like LOWER('CS%')
)
) as class
ORDER BY priority, class_id
limit 5