gpt4 book ai didi

mysql - 按最强 LIKE 排序 SQL?

转载 作者:IT老高 更新时间:2023-10-28 23:51:48 26 4
gpt4 key购买 nike

我有以下疑问:

SELECT * FROM table_name
WHERE (col_1 LIKE '%$keyword%'
OR col_2 LIKE '%$keyword%'
OR col_3 LIKE '%$keyword%')
AND .... <some optional filters> ...

是否有根据最相关的结果进行排序的策略?

最佳答案

如果您的意思是 col_1 比 col_2 更相关等等,那么:

select *
,case when col_1 like '%$keyword%' then 1
when col_2 like '%$keyword%' then 2
when col_3 like '%$keyword%' then 3
end as [priority]
from table_name
where col_1 like '%$keyword%'
or col_2 like '%$keyword%'
or col_3 like '%$keyword%'
order by [priority]

如果您的意思是最多列匹配,那么:

select *
,(case when col_1 like '%$keyword%' then 1 else 0 end) +
,(case when col_2 like '%$keyword%' then 1 else 0 end) +
,(case when col_3 like '%$keyword%' then 1 else 0 end) as [priority]
from table_name
where col_1 like '%$keyword%'
or col_2 like '%$keyword%'
or col_3 like '%$keyword%'
order by [priority] desc

关于mysql - 按最强 LIKE 排序 SQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11144394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com