首页 > 解决方案 > SQL 如果值与多列类似,则选择列

问题描述

我需要使用 ajax 创建一个自动完成搜索。建议应仅包含 10 个输入最多的结果。如果值类似于我的变量,则搜索查询必须检查多个列。

但我的问题是为此创建查询和 php 逻辑。

  1. 是否有任何插件或类似的东西?
  2. 如果列中的值像我的变量,我该如何选择?
  3. 我需要创建一个计数查询,它计算(在所有列中)“这里多久出现一次完整的单词(由空格分隔)” <-就像找到的一样(以获得相关性)

最后,我需要按相关性对找到的条目进行排序,以提供 10 个最相关的条目。

(真正的查询检查的列多于 2 列,但出于虚拟原因是 2 还可以)

选择值所在行的查询...

select * from 
(
    (select department from entries where department like '%myVariable%') 
OR 
    (select grade from entries where grade like '%myVariable%')
)

我想你知道我的意思。有人对我有任何提示、建议、示例或有用的链接吗?

提前致谢!

最好的问候,
弗里安

标签: phpmysqlsqlsearchautocomplete

解决方案


为什么不在这里使用 union all 呢?

select department from entries where department like '%myVariable%'
union all
select grade from entries where grade like '%myVariable%'

然后这应该为您订购结果:

select department, count(*) cnt from (
select department from entries where department like '%myVariable%'
union all
select grade from entries where grade like '%myVariable%')a
group by department
order by count(*) desc

推荐阅读